Ruby on rails 从数组创建哈希的最干净方法
我似乎经常遇到这种情况。我需要使用数组中每个对象的属性作为键,从数组中构建一个哈希 假设我需要一个使用ActiveRecord对象的哈希值,这些对象由它们的ID设置密钥 常见方式:Ruby on rails 从数组创建哈希的最干净方法,ruby-on-rails,ruby,arrays,hash,Ruby On Rails,Ruby,Arrays,Hash,我似乎经常遇到这种情况。我需要使用数组中每个对象的属性作为键,从数组中构建一个哈希 假设我需要一个使用ActiveRecord对象的哈希值,这些对象由它们的ID设置密钥 常见方式: ary = [collection of ActiveRecord objects] hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj } 另一种方式: ary = [collection of ActiveRecord objects] hash = Ha
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}
您可以自己添加到_散列以进行数组
class Array
def to_hash(&block)
Hash[*self.map {|e| [block.call(e), e] }.flatten]
end
end
ary = [collection of ActiveRecord objects]
ary.to_hash do |element|
element.id
end
ActiveSupport中已经有一个方法可以执行此操作
['an array', 'of active record', 'objects'].index_by(&:id)
为了记录在案,以下是实施:
def index_by
inject({}) do |accum, elem|
accum[yield(elem)] = elem
accum
end
end
可以重构为(如果您非常需要一行程序):
安装并使用他们的。最短的
# 'Region' is a sample class here
# you can put 'self.to_hash' method into any class you like
class Region < ActiveRecord::Base
def self.to_hash
Hash[*all.map{ |x| [x.id, x] }.flatten]
end
end
#“Region”是这里的一个示例类
#您可以将“self.to_hash”方法放入您喜欢的任何类中
类区域
以防有人得到普通数组
arr = ["banana", "apple"]
Hash[arr.map.with_index.to_a]
=> {"banana"=>0, "apple"=>1}
我想如果你把合并改成合并!您将避免创建一组不需要的中间散列。如果要在您的应用程序的关键路径中使用多次,那么您可能需要考虑使用Ay.Noxx{{O.O.O.ID}代替使用MaxytoToPro。<代码> NoxxB/<代码>似乎是露比的<代码> GROPY由复制。我遗漏了什么吗?group_by有一个数组作为值,而index_by假设每个键只有一个项,因此值是单个项,而不是数组。
['an array'、'of active record'、'objects']。index_by(&:id)
失败,错误名称为“数组”:未定义的方法'id':String使用Rails 4.2.5和Ruby 2.3.0I不建议为简单方法添加依赖项
arr = ["banana", "apple"]
Hash[arr.map.with_index.to_a]
=> {"banana"=>0, "apple"=>1}