In Ruby, in the context of a class method, what are instance and class variables?

If I have the following Ruby code:

class Blah
  def self.bleh
    @blih = "Hello"
    @@bloh = "World"
  end
end

What are @blih and @@ bloh? @blih is an instance variable in the Blah class, and @@ bloh is a class variable in the Blah class, right? Does this mean that @@ bloh is a variable in Blah, Class?

+5
source share
4 answers

People seem to ignore that a method is a class method.

@blih will be an instance variable of an instance of the Class class for the Bleh constant. 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 Bleh class variable:

irb(main):017:0> Bleh.class_variables
=> ["@@blah"]
irb(main):018:0> Bleh.send :class_variable_get, :@@blah
=> "World"
+4
source

There is a method in this madness ...

class Example
  @foo # class instance variable
  @@bar # class variable

  def fun1
    @baz # instance variable
  end
end

Instance variables

( @foo @baz) @ , @baz self: Class, . .


, - , . , Class, , , .

, . , . , .

, , . . : , , . .

" Ruby"
alt text

+4

, , , , .

:

class CountEm
  @@children = 0

  def initialize
    @@children += 1
    @myNumber = @@children
  end

  def whoAmI
    "I'm child number #@myNumber (out of #@@children)"
  end

  def CountEm.totalChildren
    @@children
  end
end

c1 = CountEm.new
c2 = CountEm.new
c3 = CountEm.new
c1.whoAmI              # -> "I'm child number 1 (out of 3)"
c3.whoAmI              # -> "I'm child number 3 (out of 3)"
CountEm.totalChildren  # -> 3

,

+1

[ ]

In your example, the @blih setting will not be visible outside the scope of your class method, because there is no instance inside the class method to bind the instance variable to it.

Speaking of terminology, I would say: "@@ bloh is a class variable in the Blah class", but not "a variable in the Blah class class". The class "Class" remains intact.

0
source

All Articles