Instance variable inside a singleton class

I have the following code snippet:

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 @message variable @message , Fish.action returns I can swim . Why in both cases it ignores the message I can jump . Why is this? Why is the Fish class bound to @message defined at the beginning, but not inside the singleton class?

+6
source share
1 answer

This is because class << self opens the context of the singleton class of the class:

 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:

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

Source: https://habr.com/ru/post/1011637/


All Articles