Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the downsides to declaring "instance" variables at the class scope in Ruby?

I almost never see this in Ruby code, but it seems to be valid:

class Foo
  @bar = "bar"

  def self.print_bar
    puts @bar
  end
end

My interpretation of the above that @bar is an instance variable of Foo, which is a singleton (?) instance of a Class.

This appears to be different from class variables (e.g., @@baz), which are accessible at the class scope as well as the instance scope.

What, if any, are the downsides to code like the above snippet? Or is it perfectly reasonable code?

like image 538
Dan Tao Avatar asked Dec 15 '22 14:12

Dan Tao


2 Answers

Yes, this is perfectly valid. It is also very widely used and generally recommended over class variables which have a very big scope (the class, all instances of the class, all subclasses, all instances of all subclasses, …).

There are no downsides. Classes are objects. Objects can have instance variables. Nothing to it. Ruby's object model really is much simpler than people, even authors of Ruby tutorials, would make you want to believe.

like image 117
Jörg W Mittag Avatar answered Dec 18 '22 02:12

Jörg W Mittag


One potential downside is that @bar is not available to sub-classes of Foo.

class Parent
  @bar = 3
  def self.print_bar
    puts @bar # nil
  end
end

class Child < Parent

end

Parent.print_bar # 3
Child.print_bar # nil
like image 27
meagar Avatar answered Dec 18 '22 04:12

meagar