【问题标题】:How to iterate through an array of hashes sorting the keys in Ruby如何遍历哈希数组对Ruby中的键进行排序
【发布时间】:2018-05-23 22:56:12
【问题描述】:

我有一个这样的哈希数组:

items = [{"id"=>"123", "code"=>"abc","name"=>"test", "type"=>["good"]},
   {"id"=>"555", "code"=>"ddd","name"=>"foo", "type"=>["better"]},
   {"id"=>"098", "code"=>"zyx","name"=>"bar", "type"=>["best"]}]

我正在尝试通过键对数组中的每个散列进行排序。

我试过这个:

items.each { |item| item = item.sort.to_h }

返回相同的结果:

 [{"id"=>"123", "code"=>"abc", "name"=>"test", "type"=>["good"]},
 {"id"=>"555", "code"=>"ddd", "name"=>"foo", "type"=>["better"]},
 {"id"=>"098", "code"=>"zyx", "name"=>"bar", "type"=>["best"]}]

但是当我尝试这个时:

items[0].sort.to_h

这是结果:

 {"code"=>"abc", "id"=>"123", "name"=>"test", "type"=>["good"]}

所以看起来当我使用items[x] 调用items 中的各个元素时,其中x 是数组中的索引值,它会对其进行排序。 但是我需要一个解决方案来遍历每个元素并保存排序。

有什么想法吗?

【问题讨论】:

  • 使用map 而不是each
  • 正如@Sagar 所说,使用items.map { |item| item = item.sort.to_h }
  • each 返回接收者。
  • 也不确定排序哈希的目的是什么......
  • @SagarPandya 我希望你发布答案。你的建议完全正确。

标签: arrays ruby loops hash


【解决方案1】:

如果如示例中所有哈希具有相同的键,则对键执行单一排序会更快。

sorted_keys = items.first.keys.sort
  #=> ["code", "id", "name", "type"]
items.map { |item| sorted_keys.each_with_object({}) { |k,h| h[k] = item[k] } }
  #=> [{"code"=>"abc", "id"=>"123", "name"=>"test", "type"=>["good"]},
  #    {"code"=>"ddd", "id"=>"555", "name"=>"foo", "type"=>["better"]},
  #    {"code"=>"zyx", "id"=>"098", "name"=>"bar", "type"=>["best"]}]

最后一行也可以写成

items.map { |item| sorted_keys.zip(item.values_at(*sorted_keys)).to_h }

【讨论】:

    【解决方案2】:

    我用这个解决了:

    items.map { |item| item.sort.to_h } 
    

    感谢@SagarPandya 和@Dark

    【讨论】:

    • items.map(&:sort).map(&:to_h)
    猜你喜欢
    • 1970-01-01
    • 2014-03-05
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多