In Ruby, you cannot directly set class variables (i.e. @@variable
) from outside the class:
class Foo
@@bar = "foobar"
end
# undefined method `bar=' for Foo:Class (NoMethodError)
Foo.bar = "foo"
To set a class variable, you must create a class method that allows you to set the value of the class variable:
class Foo @@bar = "foobar" # setter def self.bar=(val) @@bar = val end # getter def self.bar @@bar end end puts Foo.bar #=> "foobar" Foo.bar = "foo" puts Foo.bar #=> "foo"
It is also possible to set a class variable via a class instance by creating a setter instance method.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.