How to Access a Ruby Class Variable From an Instance?

To access the value of a class variable (i.e. @@variable) from an instance of a class, you can create a getter instance method, for example, like so:

class Foo
    @@bar = "bar"

    def bar
        @@bar
    end
end

a = Foo.new
b = Foo.new

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

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.


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.