0

所以我有一个哈希值....

 @win_moves = {
    :wm01 => {:a1=>"X", :a2=>" ", :a3=>" ", :b1=>" ", :b2=>"X", :b3=>" ", :c1=>" ", :c2=>" ", :c3=>"X"},
    :wm02 => {:a1=>" ", :a2=>"X", :a3=>" ", :b1=>" ", :b2=>"X", :b3=>" ", :c1=>" ", :c2=>"X", :c3=>" "},
    :wm03 => {:a1=>" ", :a2=>" ", :a3=>"X", :b1=>" ", :b2=>"X", :b3=>" ", :c1=>"X", :c2=>" ", :c3=>" "},
    :wm04 => {:a1=>" ", :a2=>" ", :a3=>" ", :b1=>"X", :b2=>"X", :b3=>"X", :c1=>" ", :c2=>" ", :c3=>" "},
    :wm05 => {:a1=>"X", :a2=>"X", :a3=>"X", :b1=>" ", :b2=>" ", :b3=>" ", :c1=>" ", :c2=>" ", :c3=>" "},
    :wm06 => {:a1=>" ", :a2=>" ", :a3=>" ", :b1=>" ", :b2=>" ", :b3=>" ", :c1=>"X", :c2=>"X", :c3=>"X"}
  }

我想像这样的哈希..

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

并将其与 X 值的前一个哈希 @win_moves 进行比较,这样我就会在 @win_moves[0] 上得到一个肯定的匹配(在这种情况下是答案)......我需要检查 X 的存在。

你能为我指出正确的方向吗?

4

3 回答 3

0

以下将在@win_moves 中找到与@thegrid 匹配的X 的所有键:

keys_with_x = @thegrid.select{ |k, v| v == "X" }.keys
matching_moves = @win_moves.select{ |k, v| v.select{ |k, v| v == "X" }.keys == keys_with_x }
puts matching_moves.keys
#=> wm01
于 2012-08-13T18:43:28.277 回答
0

如果您不介意破坏您的 @thegrid 哈希,您可以执行以下操作:

@winmoves.has_value? @thegrid.each { |k, v| thegrid[k] = " " if v == "O" }

如果您的 winmove 中的任何键匹配,这将返回 true。如果您需要非破坏性地执行此操作,则以下内容应该可以工作:

a_new_hash = @thegrid.inject({}) { |h, (k, v)| h[k] = " " if v == "O"; h }
@winmoves.has_value? a_new_hash
于 2012-08-13T18:43:34.203 回答
0

我认为你可以这样做:

@win_moves.any?{|k,v| v.reject{|a,b| b != 'X'} == @thegrid.reject{|c,d| d!= 'X'}}
于 2012-08-13T18:50:07.273 回答