在Ruby中将数组转换为键值对哈希表

5

如何将返回表中所有值的模型转换为名称值对哈希表

{column_value => column_value}

e.g.

[{:id => 1, :name => 'first'}, {:id => 2, :name => 'second'}, {:id => 3, :name => 'third'}]

指定:id和:name

{'first' => 1, 'second' => 2, 'third' => 3}

我想知道是否可以用一行代码完成... - Christopher
@Christopher:是的,这也可以用一行代码完成。我更新了我的答案,提供了一种另外的一行代码的解决方案。 - Pär Wieslander
你肯定可以的;看看我的答案,使用 inject - James A. Rosen
3个回答

6
您可以使用inject在一行内完成此操作:
a = [{:id => 1, :name => 'first'}, {:id => 2, :name => 'second'}, {:id => 3, :name => 'third'}]
a.inject({}) { |sum, h| sum.merge({ h[:name] => h[:id]}) }
# => {"third" => 3, "second" => 2, "first" => 1}

5
以下方法相对紧凑,但仍然易于阅读:
def join_rows(rows, key_column, value_column)
  result = {}
  rows.each { |row| result[row[key_column]] = row[value_column] }
  result
end

使用方法:

>> rows = [{:id => 1, :name => 'first'}, {:id => 2, :name => 'second'}, {:id => 3, :name => 'third'}]
>> join_rows(rows, :name, :id)
=> {"third"=>3, "second"=>2, "first"=>1}

或者,如果你想要一行代码:

>> rows.inject({}) { |result, row| result.update(row[:name] => row[:id]) }
=> {"third"=>3, "second"=>2, "first"=>1}

0
o = Hash.new
a = [{:id => 1, :name => 'first'}, {:id => 2, :name => 'second'}, {:id => 3, :name => 'third'}]
a.each {|h| o[h[:name]] = h[:id] }

puts o #{'third' => 3, 'second' => 2, 'first' => 1}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接