Sometimes I see an instance variable defined as @my_variable
. However, sometimes I see self.my_variable
. When is each used?
Instance variables (@variable
) correspond to private variables in other languages. self.myvariable
is actually not a variable, but a call to a method. Similarly, if you write self.myvariable = something
, it is actually a call to self.myvariable=(something)
. This corresponds to properties with getters and setters in other languages.
class Foo
def initialize
@bar = 42
end
def xyzzy
123
end
def xyzzy=(value)
puts "xyzzy set to #{value}!"
end
end
obj = Foo.new
puts obj.xyzzy # prints: 123
obj.xyzzy = 2 # prints: xyzzy set to 2
puts obj.bar # error: undefined method 'bar'
You can use attr_reader
and attr_accessor
to automatically define getters and setters for an instance variable. attr_reader
will only generate a getter, while attr_accessor
generates both.
class Parrot
attr_accessor :volts
def voom
puts "vooming at #{@volts} volts!"
end
end
polly = Parrot.new
polly.volts = 4000
polly.voom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With