fabersky fabersky - 14 days ago 9
Ruby Question

Sort CSV columns by value

My CSV file looks like

Name,Value1,Value2,Value3
bbb,1,3,4
aaa,5,1,7
ccc,2,2,5


Is there a way to sort by
Value1
for example?

So that the result would be


bbb,1,3,4

ccc,2,2,5

aaa,5,1,7

Answer

I found SmarterCSV, so I was able to easily do:

array_of_hashes = SmarterCSV.process('file.csv')
array_of_hashes.sort_by! { |hsh| hsh[:value1] }