Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby and CSV – How to get a column value after filtering rows

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading