3

我有以下数组(SQL 结果):

[
  {:id => 1, :field1 => "one", :field2 => "two"},
  {:id => 2, :field1 => "one", :field2 => "two"},
  ...
]

我想要的是:

{
  1 => {:field1 => "one", :field2 => "two"},
  2 => {:field1 => "one", :field2 => "two"},
  ...
}

现在我喜欢以下内容:

data = {}
result.each do |row|
  data[row[:id]] = {:field1 => row[:field1], :field2 => row[:field2]}
end

我绝对确定这是错误的方式。用 Ruby 做这件事的最好方法是什么?有没有像地图或其他东西的片段?

4

3 回答 3

6
Hash[arr.map { |h| [h.delete(:id), h] }]
于 2012-08-06T02:10:23.750 回答
2

一条线 :)

hash = arr.clone.each_with_object({}) { |e,res| res[e.delete(:id)] = e }

clone是为了不破坏arr变量

于 2012-08-05T23:59:49.057 回答
1

像这样的东西,也许?

arr = [
  {:id => 1, :field1 => "one", :field2 => "two"},
  {:id => 2, :field1 => "one", :field2 => "two"}
]

hash = arr.each_with_object({}) do |el, memo|
  id = el.delete(:id)
  memo[id] = el
end

hash # => {1=>{:field1=>"one", :field2=>"two"}, 2=>{:field1=>"one", :field2=>"two"}}
于 2012-08-05T23:45:08.050 回答