Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 549
pupeno Avatar asked Apr 08 '10 09:04

pupeno


1 Answers

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"
like image 102
user253455 Avatar answered Sep 20 '22 16:09

user253455