I saw this in some code today.
class Foo
def self.bar
@myvar = 'x'
end
end
What exactly is this accessing? As far as I can tell, this isn't accessible form instance methods. What's this called (something google-able) as I cant seem to find examples of this anywhere else.
The @myvar syntax identifies myvar as an instance variable so the real question is this:
What is
selfinside a class method?
And the answer is "self is the class object". So, @myvar is an instance variable of the Foo class object. If you add another class method:
class Foo
def self.pancakes_house
@myvar
end
end
And then do this:
Foo.bar
puts Foo.pancakes_house
You'll see x on the standard output.
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