這允許您以濾除不同搜索汽車屬性:
class Car
attr_reader :engine_size, :maximum_speed, :acceleration, :mass
def self.cars_by_attrs(cars, args = {})
return [] if cars.empty?
# Checking if all the arguments in args are valid
# instance variables on all the cars.
all_instance_vars = cars.all? do |car|
args.all? do |key, val|
car.instance_variables.include? "@#{key.to_s}".to_sym
end
end
unless all_instance_vars
raise ArgumentError.new('Instance variable not found.')
end
cars.select do |car|
args.all? do |key, val|
# Checking if the instance variables can be retrieved.
unless car.respond_to?(key)
raise ArgumentError.new('Instance variable not accessible.')
end
car.send(key) == val
end
end
end
def initialize(engine_size, maximum_speed, acceleration, mass)
@engine_size = engine_size
@maximum_speed = maximum_speed
@acceleration = acceleration
@mass = mass
@test = true
end
end
cars = []
cars << Car.new(10, 20, 5, 6)
cars << Car.new(10, 20, 7, 8)
cars << Car.new(12, 21, 9, 10)
puts Car.cars_by_attrs(cars, engine_size: 10, maximum_speed: 20)
# First two cars.
puts Car.cars_by_attrs(cars, mass: 10)
# 3rd car.
# puts Car.cars_by_attrs(cars, new: 10)
# Error !
# puts Car.cars_by_attrs(cars, test: 10)
# Error !
你們是不是基於某種共同屬性過濾汽車的陣列,或通過汽車的陣列,以獲得不同的屬性的列表? –
@ Francesco Pirrone - 前者 – pingu
您想要:1)確定哪些車具有指定屬性(例如,@engine_size = 1600','@mass = 2000'等;或2)具有相同值的組車所有的屬性?請編輯您的問題以澄清,因爲有些讀者在評論中可能會錯過您的答案。 –