If I have the following piece of Ruby code:
class Blah
def self.bleh
@blih = "Hello"
@@bloh = "World"
end
end
What exactly are @blih and @@bloh? @blih is an instance variable in the class Blah, and @@bloh is a class variable in the class Blah, correct? Does it mean that @@bloh is a variable in Blah's class, Class?
People seem to be ignoring that the method is a class method.
@blih will be instance variable of the instance of class Class for the constant Bleh. Hence:
irb(main):001:0> class Bleh
irb(main):002:1> def self.bleh
irb(main):003:2> @blih = "Hello"
irb(main):004:2> @@blah = "World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Bleh.instance_variables
=> []
irb(main):008:0> Bleh.bleh
=> "World"
irb(main):009:0> Bleh.instance_variables
=> ["@blih"]
irb(main):010:0> Bleh.instance_variable_get :@blih
=> "Hello"
@@blah will be available as a class variable of Bleh:
irb(main):017:0> Bleh.class_variables
=> ["@@blah"]
irb(main):018:0> Bleh.send :class_variable_get, :@@blah
=> "World"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With