I have parsed a CSV file with headers of ID, Name, and Address. I need to find the row(s) in the data that have a particular ID and Name. Once I find that row, I need to access the Address value.
data = CSV.parse(my_csv, headers: true)
rows = data.select { |row| row['ID'] == someId } //ids are not unique
row = rows.select { |row| row['Name'] == name } //names are unique
How do I get the Address value in this row of data? row[2] doesn’t work.
>Solution :
I need to find the row(s) in the data that have a particular ID and Name.
You can combine as many criteria as you wish in a single select():
rows = data.select {|row| row['ID'] == someId && row['Name'] == name}
In fact, you can make this boolean statement as simple or as complex as you wish. You will need to determine the exact boolean logic necessary to get the results you want.
I need to access the Address value.
To get the 'Address' column of each row selected, use map():
addresses = rows.map {|row| row['Address']}
To get the 'Address' column of the first row selected:
rows[0]['Address']
Be careful with this last one, though. It will cause an error if rows is empty.