Skip to content

Instantly share code, notes, and snippets.

@ivanoats
Forked from brookr/gist:4193101
Created March 6, 2013 00:21
Show Gist options
  • Save ivanoats/5095671 to your computer and use it in GitHub Desktop.
Save ivanoats/5095671 to your computer and use it in GitHub Desktop.
# There are 3 ways to access the value of an instance variable:
# @var, the getter method (eg: var), and self.var (where self is the instance itself)
class Car
attr_accessor :color
def shade
"Some kind of #{@color}."
end
def hue
"Looks totally #{color}ish."
end
def style
"Very #{self.color}tastic!"
end
end
>> c = Car.new
=> #<Car:0x10a3642b8>
>> c.color = "blue"
=> "blue"
>> c.shade
=> "Some kind of blue."
>> c.hue
=> "Looks totally blueish."
>> c.style
=> "Very bluetastic!"
# If we override the getter method created by attr_accessor, we
# see the difference in @var and self.var (which is really a call to the getter method)
class Car
attr_accessor :color
def shade
"Some kind of #{@color}."
end
def hue
"Looks totally #{color}ish."
end
def style
"Very #{self.color}tastic!"
end
def color
@color.upcase
end
end
>> c = Car.new
=> #<Car:0x10a392c08>
>> c.color = "blue"
=> "blue"
>> c.color
=> "BLUE"
>> c.shade
=> "Some kind of blue."
>> c.hue
=> "Looks totally BLUEish."
>> c.style
=> "Very BLUEtastic!"
# But what if we are setting a local instance variable with the exact same name?
class Car
attr_accessor :color
def shade
color = "red"
"Some kind of #{@color}."
end
def hue
color = "red"
"Looks totally #{color}ish."
end
def style
color = "red"
"Very #{self.color}tastic!"
end
def color
@color.upcase
end
end
>> c = Car.new
=> #<Car:0x10a3c0018>
>> c.color = "blue"
=> "blue"
>> c.color
=> "BLUE"
>> c.shade
=> "Some kind of blue."
>> c.hue
=> "Looks totally redish."
>> c.style
=> "Very BLUEtastic!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment