How to Access a Ruby Instance Variable From Outside the Class?

Accessing class instance variable from outside the class

In Ruby, you cannot directly access class instance variables (i.e. @variable) from outside the class:

class Foo
    def initialize
        @bar = "foobar"
    end
end

foo = Foo.new

# undefined method `bar` for Foo:Class (NoMethodError)
puts foo.bar

To access a class instance variable, you must create a class instance method that returns the value of the instance variable:

class Foo
    def initialize
        @bar = "foobar"
    end

    def bar
        @bar
    end
end

foo = Foo.new
puts foo.bar #=> "foobar"

Alternatively, you may also use attr_reader (or attr_accessor) accessor method to make an instance variable accessible from outside. These automatically generate getter methods for instance variables:

class Foo
    def initialize
        @bar = "foobar"
    end

    # creates getter for `@bar`
    attr_reader :bar
end

foo = Foo.new
puts foo.bar #=> "foobar"
class Foo
    def initialize
        @bar = "foobar"
    end

    # creates getter/setter for `@bar`
    attr_accessor :bar
end

foo = Foo.new
puts foo.bar #=> "foobar"

It is not possible to access a class instance variable from a class method.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.