这允许您以滤除不同搜索汽车属性:
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)具有相同值的组车所有的属性?请编辑您的问题以澄清,因为有些读者在评论中可能会错过您的答案。 –