簡體   English   中英

數組到ruby中鍵值對的哈希值

[英]Array to hash of key value pairs in ruby

從返回表中所有值的模型中,如何將其轉換為名稱值對的哈希值

{column_value => column_value}

例如

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

to(指定: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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM