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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With