Skip to content

Instantly share code, notes, and snippets.

@drewinglis
Created February 7, 2014 05:26
Show Gist options
  • Save drewinglis/8857720 to your computer and use it in GitHub Desktop.
Save drewinglis/8857720 to your computer and use it in GitHub Desktop.
class Car
def initialize(options)
@color = options[:color]; @make = options[:make]; @model = options[:model]
end
def color; @color; end
def make; @make; end
def model; @model; end
def color=(new_color); @color = new_color; end
def make=(new_make); @make = new_make; end
def model=(new_model); @model = new_model; end
end
$ irb
1.9.3-p125 :001 > class Car
1.9.3-p125 :002?> def initialize(options)
1.9.3-p125 :003?> @color = options[:color]; @make = options[:make]; @model = options[:model]
1.9.3-p125 :004?> end
1.9.3-p125 :005?>
1.9.3-p125 :006 > def color; @color; end
1.9.3-p125 :007?>
1.9.3-p125 :008 > def make; @make; end
1.9.3-p125 :009?>
1.9.3-p125 :010 > def model; @model; end
1.9.3-p125 :011?>
1.9.3-p125 :012 > def color=(new_color); @color = new_color; end
1.9.3-p125 :013?>
1.9.3-p125 :014 > def make=(new_make); @make = new_make; end
1.9.3-p125 :015?>
1.9.3-p125 :016 > def model=(new_model); @model = new_model; end
1.9.3-p125 :017?> end
=> nil
1.9.3-p125 :018 > Car.new(:color => "blue", :make => "ford", :model => "mustang")
=> #<Car:0x007fc6ea06df98 @color="blue", @make="ford", @model="mustang">
1.9.3-p125 :019 > c = Car.new(:color => "blue", :make => "ford", :model => "mustang")
=> #<Car:0x007fc6ea8ded80 @color="blue", @make="ford", @model="mustang">
1.9.3-p125 :020 > c.color
=> "blue"
1.9.3-p125 :021 > c.make
=> "ford"
1.9.3-p125 :022 > c.model
=> "mustang"
1.9.3-p125 :023 > c.color = "red"
=> "red"
1.9.3-p125 :024 > c.color
=> "red"
class Car
def initialize(options)
@color = options[:color]; @make = options[:make]; @model = options[:model]
end
["color", "make", "model"].each do |property|
eval "def #{property}; @#{property}; end"
eval "def #{property}=(new_#{property}); @#{property} = new_#{property}; end"
end
end
1.9.3-p125 :001 > class Car
1.9.3-p125 :002?> def initialize(options)
1.9.3-p125 :003?> @color = options[:color]; @make = options[:make]; @model = options[:model]
1.9.3-p125 :004?> end
1.9.3-p125 :005?>
1.9.3-p125 :006 > ["color", "make", "model"].each do |property|
1.9.3-p125 :007 > eval "def #{property}; @#{property}; end"
1.9.3-p125 :008?> eval "def #{property}=(new_#{property}); @#{property} = new_#{property}; end"
1.9.3-p125 :009?> end
1.9.3-p125 :010?> end
=> ["color", "make", "model"]
1.9.3-p125 :011 > c = Car.new(:color => "blue", :make => "ford", :model => "mustang")
=> #<Car:0x007f94bb8ade80 @color="blue", @make="ford", @model="mustang">
1.9.3-p125 :012 > c.color
=> "blue"
1.9.3-p125 :013 > c.make
=> "ford"
1.9.3-p125 :014 > c.model
=> "mustang"
1.9.3-p125 :015 > c.color = "red"
=> "red"
1.9.3-p125 :016 > c.color
=> "red"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment