如何从数组构建哈希

时间:2012-10-20 10:24:38

标签: ruby arrays hash

这是一个石头剪刀游戏。来自irb,game.class说它是一个数组。我希望找到赢得比赛的人的名字(在这种情况下是Player2)。

  

game = [[“Player1”,“P”],[“Player2”,“S”]]

我想到的方法是返回一个分散了名称值的Hash。然后通过该值搜索该哈希值以获取玩家名称。

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

我很感激能够帮助我理解的一些指示。

4 个答案:

答案 0 :(得分:3)

您也可以这样做。

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

答案 1 :(得分:2)

使用:

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

答案 2 :(得分:2)

使用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 }

答案 3 :(得分:0)

您可以使用Ruby的内置Array#to_h方法:

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