In ruby, if I have a CSV file that looks like this:
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
If I run my code and choose "doors" for my "wanted_attribute" and "2" for my "value" (my gets.chomp), it outputs all the cars that only have 2 doors from the CSV file:
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
How would I be able to condense this even more and make it that from this group of, doors 2, it condenses more into, color black, for example this should be the final output (outputs only color black cars):
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
This is my current code:
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
please comment code
CodePudding user response:
you can add multiple conditions inside your main logic:
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}"}
Hope it helps!