How to Set a Ruby Class Variable From an Instance?

To set the value of a class variable (i.e. @@variable) from an instance of a class, you can create a setter instance method:

class Foo
    # ...

    def bar=(val)
        @@bar = val
    end
end

For example:

class Foo
    @@bar = "bar"

    def bar=(val)
        @@bar = val
    end

    def bar
        @@bar
    end
end

a = Foo.new
b = Foo.new

puts a.bar #=> "bar"
puts b.bar #=> "bar"

a.bar = "foo"

puts a.bar #=> "foo"
puts b.bar #=> "foo"

As you can see from the example above, the class variable is accessible via class instances and have the same value shared across each instance. When the class variable value is re-assigned via one instance, the same value is reflected in all class instances.


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.