数组到ruby中键值对的哈希值

时间:2009-12-02 21:23:11

标签: ruby-on-rails ruby

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

{column_value => column_value}

e.g。

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

to(指定:id和:name)

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

3 个答案:

答案 0 :(得分: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}

答案 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}

答案 2 :(得分: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}