0

So I have a hash of hashes....

 @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"}
  }

and I want to take a hash like such..

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

and compare it to the previous hash @win_moves for the X values so I would get a positive match on @win_moves[0] (the answer in this case)...I need to check for the presence of the X.

Can you point me in the right direction?

4
  • Is it on purpose that \@thegrid contains "O" and \@win_moves contains " "?
    – davidrac
    Aug 13, 2012 at 18:27
  • yes. I need to test against the location of the X's regardless of empty spaces or the presence of O's.
    – thefonso
    Aug 13, 2012 at 18:41
  • We also need to know what you need in return. Do you need to know which one matched or just that one did match? Aug 13, 2012 at 18:48
  • either...but for simplicity...just that one did match
    – thefonso
    Aug 13, 2012 at 18:51

3 Answers 3

0

If you don't mind being destructive of your @thegrid hash you can do the following:

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

That will return true if any of the keys in your winmoves are matched. Ff you need to do it non-destructively the following should work:

a_new_hash = @thegrid.inject({}) { |h, (k, v)| h[k] = " " if v == "O"; h }
@winmoves.has_value? a_new_hash
0

I think you can do that:

@win_moves.any?{|k,v| v.reject{|a,b| b != 'X'} == @thegrid.reject{|c,d| d!= 'X'}}
0

The following would find all keys in @win_moves that have the matching Xs as @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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.