向类添加方法

时间:2018-02-23 10:04:54

标签: ruby

我需要将方法color添加到类Car以获取此信息:

car = Car.new
car.color
# => 'red'

这是我的代码:

car.color
# => undefined method `color'

2 个答案:

答案 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"