Wolf_Tru
Wolf_Tru

Reputation: 563

Selecting hash element if 'key' or 'value' contains a value in ruby

I am wondering if there was a way to search hash table for both key and values containing a value.

currently I'm doing this:

 #for this example say 
 bot,input = "rock","scissors" 

hash = Hash['rock', 'scissors', 'scissors', 'paper', 'paper', 'rock'] 
outcome = ([hash.rassoc(bot), hash.assoc(bot)] &  [hash.rassoc(input),hash.assoc(input)]).flatten

Outcome here finds all hash elements that contain bot and input; then checks to see which one they have in common. Just wondering if there was a method I over looked to return what i'd want:

outcome = [hash.rassoc(bot), hash.assoc(bot)]

Upvotes: 1

Views: 92

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Is this what you are looking for?

winners = { "rock"=>"scissors", "scissors"=>"paper", "paper"=>"rock" } 

def outcome(winners, player, opponent)
  return :win  if winners.any? { |pair| pair == [player, opponent] }
  return :lose if winners.any? { |pair| pair == [opponent, player] }
  return :tie
end

outcome winners, "rock", "scissors" #=> :win
outcome winners, "scissors", "rock" #=> :lose
outcome winners, "rock", "rock"     #=> :tie

Upvotes: 3

Related Questions