Skip to content

Instantly share code, notes, and snippets.

@abrahamsangha
Last active December 18, 2015 03:19
Show Gist options
  • Save abrahamsangha/5717657 to your computer and use it in GitHub Desktop.
Save abrahamsangha/5717657 to your computer and use it in GitHub Desktop.
The instructions were to fix this bad code with a method_missing method.
class Person
def initialize(name, age, incoming_race)
@name = name
@age = age
self.race = incoming_race
end
def nam
@name.split.map(&:capitalize).join(" ")
end
def agE
@age
end
def method_missing(m, *args)
if m.to_s =~ /name/
self.nam
elsif m.to_s =~ /age/
self.agE
elsif m.to_s =~ /race=/ #So, when person.race= is called, @race is assigned to the argument
@race = args[0] #Kind of like attr_writer
elsif m.to_s =~ /race/
@race.capitalize #like attr_reader
else
super
end
end
end
person = Person.new("kurt vonnegut", 89, "caucasian")
assert_equal person.name, "Kurt Vonnegut"
assert_equal person.race, "Caucasian"
assert_equal person.age, 89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment