ruby-on-rails - 从数组创建哈希的最简洁方法

标签 ruby-on-rails ruby arrays hash

我似乎经常遇到这种情况。我需要使用数组中每个对象的属性作为键从数组构建哈希。

比方说我需要一个散列的例子使用 ActiveRecord objecs 通过他们的 ids 键控 常用方式:

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

另一种方式:

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

梦想之路: 我可以而且可能会自己创建这个,但是 Ruby 或 Rails 中有什么东西可以做到这一点吗?

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

最佳答案

ActiveSupport 中已经有一个方法可以做到这一点。

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

作为记录,这里是实现:

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

可以重构为(如果您急需单行代码):

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

关于ruby-on-rails - 从数组创建哈希的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412771/

相关文章:

ruby-on-rails - 如何在本地将所有 'perform_later' s 转换为 'perform_now' s?

mysql - 在 Ruby 中使用 SQLite 还是 MySQL?

php - 如何从 php 数组生成唯一的字符串

c++ - 如何将数组复制到更大的数组并将零添加到未使用的空间? C++

javascript - 过滤 js 中长度小于 < 50 个字符的内容

ruby-on-rails - "gem.add_dependency"另一个本地 gem

ruby-on-rails - rails 3.2 : Replace null values with empty string from json serialization

javascript - Rails 不显眼的 javascript (UJS) ajax :before append data params

ruby - Selenium RC :How to launch Interactive testing with Multiple browsers

ruby - 在 Rails 3 中创建一个 plist