如何使用Ruby Array的元素作为Hash键?

时间:2012-08-17 03:16:33

标签: ruby

让我改革这个问题:

我有两个哈希我正在比较。在我的代码中的某个时刻,我得到了一个响应,例如..

@moves = {:wm01 => {:a1=>"O", :a2=>" ", :a3=>" ", :b1=>" ", :b2=>"O", :b3=>" ", :c1=>" ", :c2=>" ", :c3=>" "}

这对应于答案密钥哈希......

@anskey={
    :wm01=>":c3",:wm02=>":c2",:wm03=>":c1",:wm04=>":b3",:wm05=>":b1",:wm06=>":a3",:wm07=>":a2",:wm08=>":a1",
    :wm09=>":a3",:wm10=>":c1",:wm11=>":a1",:wm12=>":c3",:wm13=>":c3",:wm14=>":c1",:wm15=>":c3",:wm16=>":a1",
    :wm17=>":b1",:wm18=>":b2",:wm19=>":b3",:wm20=>":a2",:wm21=>":b2",:wm22=>":b2",:wm23=>":c2",:wm24=>":b2"
  }

在这种情况下我需要迭代@anskey,其中@ moves.keys == @ anskey.keys

(嗯。我可能刚刚回答了我自己的问题)

然后设置....

my_answer_is = @anskey.value

希望这更清楚。

下面的原始“问题”:

这是漫长的一天,我的屏幕疲劳......

我有这个......

str = [:wm24]

想说...

@anskey[:wm24]

这是错误的..

@anskey[str]

什么是对的?

@anskey[?]

1 个答案:

答案 0 :(得分:3)

您可以将数组中的第一个元素传递给它:

@anskey[str.first]

或者,如果要根据索引(数组中的位置)访问元素,则从零开始计数。所以在这种情况下:

@anskey[str[0]]