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

noj0wjuj  于 2022-10-15  发布在  Ruby
关注(0)|答案(1)|浏览(113)

在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

如果我运行我的代码并选择“Doors”作为我的“WAND_ATTRIBUTE”,选择“2”作为我的“VALUE”(我的gets.chomp),它将输出CSV文件中只有两个门的所有汽车:

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

请评论代码

yh2wf1be

yh2wf1be1#

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

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}"}

希望它能帮上忙!

相关问题