在使用CSV文件时操作一个类以更改另一个类



在ruby中,如果我有一个CSV文件,它看起来像这样:

make,model,color,doors
dodge,charger,black,4
ford,focus,blue,5
nissan,350z,black,2
mazda,miata,white,2
honda,civid,brown,4
corvette,stingray,red,2
ford,fiesta,blue,5
bmw,m4,black,2
audi,a5,blue,2
subaru,brz,black,2
lexus,rc,black,2

如果我运行我的代码并选择";门";对于我的";wanted_attribute";以及";2〃;对于我的";值";(mygets.chomp(,它从CSV文件中输出所有只有2个车门的汽车:

make: nissan, model: 350z, color: black, doors: 2
make: mazda, model: miata, color: white, doors: 2
make: corvette, model: stingray, color: red, doors: 2
make: bmw, model: m4, color: black, doors: 2
make: audi, model: a5, color: blue, doors: 2
make: subaru, model: brz, color: black, doors: 2
make: lexus, model: rc, color: black, doors: 2

我如何能够将其浓缩得更多,并使其从这组车门2中浓缩成更多的黑色,例如,这应该是最终输出(仅输出彩色黑色汽车(:

make: nissan, model: 350z, color: black, doors: 2
make: bmw, model: m4, color: black, doors: 2
make: subaru, model: brz, color: black, doors: 2
make: lexus, model: rc, color: black, doors: 2

这是我当前的代码:

require "csv"
class Car
attr_accessor :make, :model, :color, :doors
def initialize(make, model, color, doors)
@make, @model, @color, @doors = make, model, color, doors
end
def to_s
"make: #{self.make}, model: #{self.model}, color: #{self.color}, doors: #{self.doors}"
end
end
cars = CSV.read("so.csv").map{|car| Car.new(car[0], car[1], car[2], car[3])}
print "Select attribute: "
wanted_attribute = gets.chomp
print "Select value: "
value = gets.chomp
wanted_cars = cars.select{|car| car.instance_variable_get("@#{wanted_attribute}") == value}
puts wanted_cars

请评论代码

您可以在主逻辑中添加多个条件:

print "Select color attribute: "
wanted_color_attribute = gets.chomp
print "Select color: "
color = gets.chomp
wanted_cars = cars.select{|car| car.instance_variable_get("@#{wanted_attribute}") == value && car.instance_variable_get("@#{wanted_color_attribute}") == "#{color}"}

希望它能有所帮助!

最新更新