Ruby 在没有实例的情况下调用方法
我有以下代码:Ruby 在没有实例的情况下调用方法,ruby,Ruby,我有以下代码: class Cars attr_accessor :car_make attr_accessor :car_model def initialize(make, model) self.car_make = make self.car_model = model end end 我想知道是否有可能实现list\u cars方法 并按如下方式调用该方法: ford = Cars.new("Ford" ,"F-150") honda = Cars.n
class Cars
attr_accessor :car_make
attr_accessor :car_model
def initialize(make, model)
self.car_make = make
self.car_model = model
end
end
我想知道是否有可能实现list\u cars
方法
并按如下方式调用该方法:
ford = Cars.new("Ford" ,"F-150")
honda = Cars.new("Honda", "CRV")
list_cars(ford, honda)
i、 例如,不必从现有对象调用它。我试过这个:
def list_cars(first_car, second_car)
puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
end
我意识到这段代码缺少一些东西,但我不知道那是什么。将其作为类方法:
class Cars
def self.list_cars(first_car, second_car)
puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
end
end
然后,您可以简单地称之为:
Cars.list_cars(car1, car2)
您可以找到有关类方法的更多信息
这是否是正确的方法(或新模块,或作为对象空间中的一种方法)取决于您的项目体系结构。Markus的答案是人们通常会采用的方法(并且可能是首选方法,因为这不会污染主名称空间)。但这不是你想要的解决方案。为了实现您想要的功能,您通常在
内核上实现该方法
module Kernel
def list_cars(first_car, second_car)
puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
end
end
您的代码应该可以工作-您遇到了什么错误?main:Object(NoMethodError)list\u cars
的未定义方法'list\u cars'在类cars
之外实现,对吗?你的代码对我有用。是的,在课堂外实现。呵呵。。。真奇怪!啊,太好了,就是这样。也谢谢你关于资源的提示-我在自学。。。