所以我有哈希哈希......
@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"}
并将其与之前的哈希值@win_moves进行比较,因此我会得到@win_moves [0]的肯定匹配(在这种情况下的答案)......我需要检查是否存在X.
你能指出我正确的方向吗?
答案 0 :(得分:0)
以下内容会找到@win_moves中匹配X为@thegrid的所有键:
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
答案 1 :(得分:0)
如果您不介意破坏@thegrid哈希,可以执行以下操作:
@winmoves.has_value? @thegrid.each { |k, v| thegrid[k] = " " if v == "O" }
如果winmoves中的任何键匹配,则返回true。如果您需要非破坏性地执行以下操作:
a_new_hash = @thegrid.inject({}) { |h, (k, v)| h[k] = " " if v == "O"; h }
@winmoves.has_value? a_new_hash
答案 2 :(得分:0)
我认为你可以这样做:
@win_moves.any?{|k,v| v.reject{|a,b| b != 'X'} == @thegrid.reject{|c,d| d!= 'X'}}