@used inside the self method does what exactly?

I saw this in some code today.

class Foo
  def self.bar 
    @myvar = 'x'
  end 
end 

What exactly is this access? As far as I can tell, these are inaccessible form instance methods. That this is called (something google-capable) as I cannot find examples of this elsewhere.

+3
source share
3 answers

The syntax @myvaridentifies myvaras an instance variable, so the real question is this:

What is selfinside a class method?

And the answer " selfis a class object." Thus, @myvaris an instance variable of a class object Foo. If you add another class method:

class Foo
    def self.pancakes_house
        @myvar
    end
end

And then do the following:

Foo.bar
puts Foo.pancakes_house

You will see xthe standard output.

+7

, Foo.

>> Foo.bar
>> Foo.instance_variable_get("@myvar") 
=> 'x'

, , class << self; attr_accessor :myvar; end , :

>> Foo.bar
>> Foo.myvar
=> 'x'
+3

For googling, this is sometimes called a "class instance variable". That is, an instance variable of an object that is simply a class.

+1
source

All Articles