Ruby CSV::Table sort in place

一世执手 提交于 2020-01-06 20:09:34

问题


I'm sorting a CSV::Table object. I have a table with headers ("date", "amount", "source") and O(50) entries.

Input:

data = CSV.table('filename.csv', headers:true) # note headers are :date, :source, :amount

amounts = []
data[:amount].each {|i| amounts << i.to_f}

data.sort_by! {|row| row[:amount]} 
# error - not a defined function

data = data.sort_by {|row| row[:amount]} 
# sorted but data is now an array not CSV::Table. would like to retain access to headers

I want a bang function to sort the table in place by the "amount" column without loosing the CSV::Table structure. Specifically, I want the result to be a CSV::Table, so that I still have access to the headers. Right now, I'm getting an Array, which is not what I want.

I'm sure there is an easier way to do this, especially with the CSV::Table class. Any help?


回答1:


You can use:

CSV::Table.new(data) to convert Array to CSV::Table object if that is what you want.

sort_by is a method from Enumerable module which will always return an array when block is given as an argument



来源:https://stackoverflow.com/questions/37786098/ruby-csvtable-sort-in-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!