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.
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.