Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby instance variables and methods

Sometimes I see an instance variable defined as @my_variable. However, sometimes I see self.my_variable. When is each used?

like image 578
Justin Avatar asked May 18 '11 01:05

Justin


1 Answers

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   
like image 163
hammar Avatar answered Oct 01 '22 10:10

hammar