【问题标题】:How is the best way to merge array of hashes based on same value of some key?基于某个键的相同值合并哈希数组的最佳方法是什么?
【发布时间】:2016-10-07 15:31:27
【问题描述】:

我有一些具有相同键的哈希数组。如下所示:

entities = [
  {type: :user, name: 'Tester', phone: '0000-0000'},
  {type: :user, name: 'Another User', phone: '0000-0000'},
  {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
  {type: :user, name: 'John Appleseed', phone: '0000-0000'},
  {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
]

我需要根据某个键的值来组织它们,用基于原始散列的某个键的值的键生成一个新的散列,例如type

我这样做是为了组织:

by_type = {}
entities.each do |entity|
  by_type[entity[:type]] ||= []
  by_type[entity[:type]] << entity
end

得到我需要的结果:

by_type = {
  user: [
    {type: :user, name: 'Tester', phone: '0000-0000'},
    {type: :user, name: 'Another User', phone: '0000-0000'},
    {type: :user, name: 'John Appleseed', phone: '0000-0000'}
  ],
  company: [
    {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
    {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
  ]
}

还有其他方式或优雅的方法来组织这个吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 hash


    【解决方案1】:

    你可以使用group_by:

    entities.group_by { |entity| entity[:type] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 2015-07-18
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 2010-10-11
      相关资源
      最近更新 更多