问题
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