Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ used inside a self method is doing what exactly?

Tags:

ruby

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.

like image 329
John Hinnegan Avatar asked Dec 08 '25 02:12

John Hinnegan


1 Answers

The @myvar syntax identifies myvar as an instance variable so the real question is this:

What is self inside 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.

like image 136
mu is too short Avatar answered Dec 10 '25 19:12

mu is too short