如何将返回表中所有值的模型转换为名称值对哈希表
{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}
如何将返回表中所有值的模型转换为名称值对哈希表
{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}
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}
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}
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}
inject
。 - James A. Rosen