按日期字段对哈希数组进行排序
Sorting an array of hashes by a date field
我有一个包含许多哈希数组的对象,其中一个我想按 'date' 键中的值排序。
@array['info'][0] = {"name"=>"personA", "date"=>"23/09/1980"}
@array['info'][1] = {"name"=>"personB", "date"=>"01/04/1970"}
@array['info'][2] = {"name"=>"personC", "date"=>"03/04/1975"}
我尝试了使用 Date.parse 和 collect 的各种方法,但无法找到好的解决方案。
编辑:
要清楚我想对原始数组进行排序
@array['info'].sort_by { |i| Date.parse i['date'] }.collect
如何以 'Ruby-ist' 的方式优雅地解决这个问题。谢谢
整体看起来不错。虽然您可以删除 collect
调用,因为它不需要并使用 sort_by!
就地修改数组(而不是重新分配):
@array['info'].sort_by! { |x| Date.parse x['date'] }
另一种不需要将日期字符串转换为日期对象的方法如下。
代码
def sort_by_date(arr)
arr.sort_by { |h| h["date"].split('/').reverse }
end
如果arr
要原地排序,使用Array#sort_by! rather than Enumerable#sort_by。
例子
arr = [{ "name"=>"personA", "date"=>"23/09/1980" },
{ "name"=>"personB", "date"=>"01/04/1970" },
{ "name"=>"personC", "date"=>"03/04/1975" }]
sort_by_date(arr)
#=> [{ "name"=>"personB", "date"=>"01/04/1970" },
# { "name"=>"personC", "date"=>"03/04/1975" },
# { "name"=>"personA", "date"=>"23/09/1980" }]
说明
对于示例中的arr
,sort_by
将arr
的第一个元素传递到它的块中,并将其赋值给块变量:
h = { "name"=>"personA", "date"=>"23/09/1980" }
然后计算:
a = h["date"].split('/')
#=> ["23", "09", "1980"]
然后:
b = a.reverse
#=> ["1980", "09", "23"]
类似地,我们得到b
等于:
["1970", "04", "01"]
和
["1975", "04", "03"]
对于 arr
的其他两个元素中的每一个。
如果您查看 Array#<=> 的文档,您会发现这三个数组的顺序如下:
["1970", "04", "01"] < ["1975", "04", "03"] < ["1980", "09", "23"]
无需将字符串元素转换为整数。
我有一个包含许多哈希数组的对象,其中一个我想按 'date' 键中的值排序。
@array['info'][0] = {"name"=>"personA", "date"=>"23/09/1980"}
@array['info'][1] = {"name"=>"personB", "date"=>"01/04/1970"}
@array['info'][2] = {"name"=>"personC", "date"=>"03/04/1975"}
我尝试了使用 Date.parse 和 collect 的各种方法,但无法找到好的解决方案。
编辑: 要清楚我想对原始数组进行排序
@array['info'].sort_by { |i| Date.parse i['date'] }.collect
如何以 'Ruby-ist' 的方式优雅地解决这个问题。谢谢
整体看起来不错。虽然您可以删除 collect
调用,因为它不需要并使用 sort_by!
就地修改数组(而不是重新分配):
@array['info'].sort_by! { |x| Date.parse x['date'] }
另一种不需要将日期字符串转换为日期对象的方法如下。
代码
def sort_by_date(arr)
arr.sort_by { |h| h["date"].split('/').reverse }
end
如果arr
要原地排序,使用Array#sort_by! rather than Enumerable#sort_by。
例子
arr = [{ "name"=>"personA", "date"=>"23/09/1980" },
{ "name"=>"personB", "date"=>"01/04/1970" },
{ "name"=>"personC", "date"=>"03/04/1975" }]
sort_by_date(arr)
#=> [{ "name"=>"personB", "date"=>"01/04/1970" },
# { "name"=>"personC", "date"=>"03/04/1975" },
# { "name"=>"personA", "date"=>"23/09/1980" }]
说明
对于示例中的arr
,sort_by
将arr
的第一个元素传递到它的块中,并将其赋值给块变量:
h = { "name"=>"personA", "date"=>"23/09/1980" }
然后计算:
a = h["date"].split('/')
#=> ["23", "09", "1980"]
然后:
b = a.reverse
#=> ["1980", "09", "23"]
类似地,我们得到b
等于:
["1970", "04", "01"]
和
["1975", "04", "03"]
对于 arr
的其他两个元素中的每一个。
如果您查看 Array#<=> 的文档,您会发现这三个数组的顺序如下:
["1970", "04", "01"] < ["1975", "04", "03"] < ["1980", "09", "23"]
无需将字符串元素转换为整数。