我需要将方法color
添加到类Car
以获取此信息:
car = Car.new
car.color
# => 'red'
这是我的代码:
car.color
# => undefined method `color'
答案 0 :(得分:3)
如果您想为所有车型添加方法,请执行Marek建议的操作。或者,您只能将color
添加到此 car
。
car = Car.new
def car.color
'red'
end
car.color # => "red"
another_car = Car.new
another_car.color # ~> -:11:in `<main>': undefined method `color' for #<Car:0x00007faba40b9da0> (NoMethodError)
答案 1 :(得分:2)
您只需重新打开Car
课程:
class Car
def wheel_count
4
end
end
car = Car.new
car.wheel_count # => 4
car.color # ~> -:9:in `<main>': undefined method `color' for #<Car:0x00007fc06794c918> (NoMethodError)
class Car
def color
'red'
end
end
car = Car.new
car.wheel_count # => 4
car.color # => "red"