Search code examples
rubyhashgroup

Making a CSV file into a hash and then grouping by criteria


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

how would I be able to change this to a hash and be able to group them together by amount of doors or another parameter from the header, for example, the program asks the user for the amount of doors, if the user enters "2" then only the lines that have "2" for doors will be outputted (please comment)


Solution

  • I don't believe a hash table is what you want as you would have to make a new one for each attribute. Here's a way of doing it using a Car class

        require "csv"
        
        
        class Car
            attr_accessor :make, :model, :color,:door
        
            def initialize(make, model, color, door)
                @make, @model, @color, @door = make, model, color, door
            end
        
            def to_s
                "Make: #{self.make}, Model: #{self.model}, Color: #{self.color}, Door: #{door}"
            end
        end
        
        cars = CSV.read("so.csv").map{|car| Car.new(car[0], car[1], car[2], car[3])}
        
        attributeWanted = gets.chomp
        value = gets.chomp
        
        
        wantedCars = cars.select{|car| car.instance_variable_get("@#{attributeWanted}") == value}
        puts(wantedCars)
    
    

    Result: door 5 Make: ford, Model: focus, Color: blue, Door: 5 Make: ford, Model: fiesta, Color: blue, Door: 5