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

a =
b =

puts #=> "bar"
puts #=> "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.