我想知道是否有办法搜索哈希表以获取包含值的键和值。
目前我正在这样做:
#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 = [hash.rassoc(bot), hash.assoc(bot)]
答案 0 :(得分:3)
这是你在找什么?
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