Hi --

On Fri, 5 Mar 2004, Simon Strandgaard wrote:

> Yes.. however if I invoke 'install' instead of above 'puts',
> then 
> b.rb:3: undefined local variable or method `install' for #<Class:#<String:0x810a684>> (NameError)
> 
> 
> server> ruby b.rb
> nil
> b.rb:9: warning: instance variable @state not initialized
> change state  old=  new=true
> true
> true
> server> cat b.rb 
> obj = "im just some random object"
> class << obj
>   #install # why doesn't this work?
>   def install
>     puts "install"
>     @state = false
>   end
>   attr_reader :state
>   def change_state(state)
>     puts "change state  old=#{@state}  new=#{state}"
>     @state = state
>   end
> end
> p obj.state
> p obj.change_state(true)
> p obj.state
> server>

There are two things standing in your way here:

1. If you do this:

  class <whatever>
    my_method
  end

then you're calling a method on the Class object itself.  (Note that
"<whatever>" can be a constant or a "<< obj" expression.  Both of
these forms do essentially the same thing, namely create and/or open
up a particular class.)

2. You can't call a method before you define it.  Mind you, you 
haven't actually defined it :-)  (the class method install, that
is).

  obj = Object.new
  class << obj
    def self.install
      #...
    end

    install
  end


David

P.S. I have no idea if you'll get this, since the news gateway still
isn't working and I don't know if you're on ruby-talk.  Sigh.  I
believe it's being looked into.

-- 
David A. Black
dblack / wobblini.net