Ruby CSV ::表排序到位 [英] Ruby CSV::Table sort in place

查看:154
本文介绍了Ruby CSV ::表排序到位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在排序 CSV :: Table 对象。我有一个表头(dateamountsource

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

输入:

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

我想要一个bang函数, code>amount列,而不会丢失 CSV :: Table 结构。具体来说,我想要的结果是一个CSV ::表,以便我仍然可以访问的头。现在,我得到一个数组,这不是我想要的。

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.

我相信有一个更容易的方法来做到这一点,特别是与 CSV :: Table 类。任何帮助?

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

推荐答案

您可以使用:

CSV :: Table.new(data)将数组转换为CSV :: Table对象,如果你想要的话。

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

sort_by 是一个来自Enumerable模块的方法,当块作为参数时,它总是返回一个数组

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

这篇关于Ruby CSV ::表排序到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆