簡體   English   中英

如何從數組構建哈希

[英]How to build hash from array

這是一個石頭剪刀布游戲。 從irb中,game.class表示這是一個數組。 我希望找到贏得比賽的人的名字(在本例中為Player2)。

游戲= [[“ Player1”,“ P”],[“ Player2”,“ S”]]

我想到的方法是返回一個散列了名稱值的哈希值。 然后通過該值搜索該哈希以獲取玩家名稱。

h = Hash.new(0)
game.collect do |f|
  h[f] = f[1]
end
h
#=> {["Player1", "P"]=>"P", ["Player2", "S"]=>"S"}

這很近但是沒有雪茄。 我想要

{"Player1" => "P", "Player2" => "S"}

我再次嘗試使用注入方法:

game.flatten.inject({}) do |player, tactic| 
  player[tactic] = tactic  
  player 
end
#=> {"Player1"=>"Player1", "P"=>"P", "Player2"=>"Player2", "S"=>"S"}

這不起作用:

Hash[game.map {|i| [i(0), i(1)] }]
#=> NoMethodError: undefined method `i' for main:Object

我希望能找到一些可以幫助我理解的東西。

您也可以這樣做。

game = [["Player1", "P"], ["Player2", "S"]]
#=> [["Player1", "P"], ["Player2", "S"]]
Hash[game]
#=> {"Player1"=>"P", "Player2"=>"S"}

采用:

game.inject({}){ |h, k| h[k[0]] = k[1]; h }

使用each_with_object意味着您不需要在塊中包含兩個語句,就像xdazz的答案一樣

game.each_with_object({}){ |h, k| h[k[0]] = k[1] }

您可以通過破壞第二個塊參數來使其更加可讀

game.each_with_object({}){ |hash, (name, tactic)| hash[name] = tactic }

您可以為此使用Ruby內置的Array#to_h方法:

game.to_h
#=> {"Player1"=>"P", "Player2"=>"S"}

暫無
暫無

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

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