从阵列中创建一个哈希干净的方法 [英] Cleanest way to create a Hash from an Array

查看:113
本文介绍了从阵列中创建一个哈希干净的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎经常遇到这样的。我需要阵列作为密钥使用的每个对象的属性从数组建立一个散列

可以说,我需要例如哈希使用由它们的ID键控的ActiveRecord objecs
常见的方式:

 元= [ActiveRecord对象的集合]
哈希= ary.inject({}){|哈希,OBJ |哈希[obj.id] = OBJ}

另一个方式:

 元= [ActiveRecord对象的集合]
哈希散列= [*(ary.map {| OBJ | [obj.id,OBJ]})。压扁]

梦想之路:
我可以并可能制造出这个自己,但有使用Ruby或者Rails任何会这样?

 元= [ActiveRecord对象的集合]
哈希= ary.to_hash&放大器;:ID
#或者至少
哈希= ary.to_hash {| OBJ | obj.id}


解决方案

有已经在的ActiveSupport才会这样的方法。

  ['活动记录的'阵列','对象'] index_by。(安培;:ID)

和公正的记录,这里的实现:

 高清index_by
  注({})做| ACCUM,ELEM |
    ACCUM [产量(ELEM)] = ELEM
    ACCUM
  结束
结束

这本来是重构到(如果你的俏皮话是绝望):

 高清index_by
  注({}){|哈希,ELEM | hash.merge!(收益率(ELEM)=> ELEM)}
结束

I seem to run into this very often. I need to build a Hash from an array using an attribute of each object in the array as the key.

Lets say I need a hash of example uses ActiveRecord objecs keyed by their ids Common way:

ary = [collection of ActiveRecord objects]
hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj }

Another Way:

ary = [collection of ActiveRecord objects]
hash = Hash[*(ary.map {|obj| [obj.id, obj]}).flatten]

Dream Way: I could and might create this myself, but is there anything in Ruby or Rails that will this?

ary = [collection of ActiveRecord objects]
hash = ary.to_hash &:id
#or at least
hash = ary.to_hash {|obj| obj.id}

解决方案

There is already a method in ActiveSupport that does this.

['an array', 'of active record', 'objects'].index_by(&:id)

And just for the record, here's the implementation:

def index_by
  inject({}) do |accum, elem|
    accum[yield(elem)] = elem
    accum
  end
end

Which could have been refactored into (if you're desperate for one-liners):

def index_by
  inject({}) {|hash, elem| hash.merge!(yield(elem) => elem) }
end

这篇关于从阵列中创建一个哈希干净的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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