Home > database >  Outputting single row from CSV file from specific header name
Outputting single row from CSV file from specific header name

Time:10-18

In ruby 3.1.2, using this CSV file:

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

How would I be able to print out just one of the rows specific to the email. For example, the user enters: "[email protected]", and this is the output: lexus,rc,black,2,[email protected]

CodePudding user response:

csv = CSV.read('filename.csv', headers: true)
row = csv.find {|row| row['email'] == '[email protected]'}
 => #<CSV::Row "make":"lexus" "model":"rc" "color":"black" "doors":"2" "email":"[email protected]"> 

then map the output to a model if you want.

  • Related