mhaseeb mhaseeb - 1 month ago 6
Ruby Question

Instance variable inside singleton class

I have the following piece of code:

class Fish
# @message = "I can swim"

class << self
@message = "I can jump!"
define_method(:action) { @message }
end
end


Fish.action => nil


As soon as I uncomment the above
@message
variable,
Fish.action
returns
I can swim
. Why in both cases it is ignoring the
I can jump
message. Why is that? Why is Fish class being binded to the
@message
defined at the start but not inside the
singleton
class?

ndn ndn
Answer

It's because class << self opens the class' singleton class context:

class Foo
  p self # Foo
  class << self
    p self # #<Class:Foo>
    define_method(:bar) { p self } # Foo
  end
end
Foo.bar

You can verify that by:

Fish.singleton_class.instance_variable_get(:@action) # => "I can jump!"
Comments