ruby - Initializing instance variables inside << self blocks -
specifically, why following code output nil instead of 1?
class foo class << self @bar = 1 def bar @bar end end end p foo.bar
in << self block, self instance of #<class:foo>.
class foo puts "self in foo declaration is: #{self} #{self.class} #{self.object_id}" class << self @bar = 1 puts "self in foo.self declaration is: #{self} #{self.class} #{self.object_id}" def bar puts "self in class method #{self} #{self.class} #{self.object_id}" @bar end end end p foo.bar this code outputs:
self in foo declaration is: foo class 69910818825400 self in foo.self declaration is: #<class:foo> class 69910818825380 self in class method foo class 69910818825400 so slight modification code, works expected, is:
class foo @bar = 1 class << self def bar @bar end end end p foo.bar
Comments
Post a Comment