Skip to content

Instantly share code, notes, and snippets.

@duqcyxwd
Created May 12, 2013 00:50
Show Gist options
  • Save duqcyxwd/5561961 to your computer and use it in GitHub Desktop.
Save duqcyxwd/5561961 to your computer and use it in GitHub Desktop.
A Shortcut for Creating Getters and Setters
# Getters and Setters
class Car
def color=(c)
@color = c
end
def color
@color
end
end
ferrari = Car.new
ferrari.color = "Red"
ferrari.color #=> "Red"
#Getters and Setters with attr_*
class Car
attr_accessor :color
attr_reader :speed
attr_writer :lights
def turn_on(on)
if on
@speed = 10
else
@speed = 0
end
end
def accelerate
@speed += 10
end
def light_setting
if @lights == :position_one
"Lights are off"
elsif @lights == :position_two
"Lights are on (low beam)"
elsif @lights == :position_three
"Lights are on (high beam)"
end
end
end
ferrari = Car.new
# attr_accessor
ferrari.color = "Red"
ferrari.color #=> "Red"
# attr_reader
ferrari.turn_on(true)
ferrari.speed #=> 10
ferrari.accelerate
ferrari.speed #=> 20
# attr_writter
ferrari.lights = :position_one
ferrari.light_setting #=> "Lights are off"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment