def winner(p1, p2)
wins = {rock: :scissors, scissors: :paper, paper: :rock}
{true => p1, false => p2}[wins[p1] == p2]
end
从这个问题:HW impossibility?: "Create a rock paper scissors program in ruby WITHOUT using conditionals"
答案 0 :(得分:6)
我承认,对于新手程序员来说,这不是最易读的代码。我重写了它,提取了一些变量并添加了注释。希望你现在能更好地理解它。
def winner(p1, p2)
# rules of dominance, who wins over who
wins = {
rock: :scissors,
scissors: :paper,
paper: :rock
}
# this hash is here to bypass restriction on using conditional operators
# without it, the code would probably look like
# if condition
# p1
# else
# p2
# end
answers = {
true => p1,
false => p2
}
# given the choice of first player, which element can he beat?
element_dominated_by_first_player = wins[p1]
# did the second player select the element that first player can beat?
did_player_one_win = element_dominated_by_first_player == p2
# pick a winner from our answers hash
answers[did_player_one_win]
end
winner(:rock, :scissors) # => :rock
winner(:rock, :paper) # => :paper
winner(:scissors, :paper) # => :scissors
答案 1 :(得分:1)
你可以看到这是一款摇滚剪纸游戏。 def
关键字启动方法定义。而end
表示方法的结束。
方法的主体wins = {rock: :scissors, scissors: :paper, paper: :rock}
的第一行定义了一个名为wins
的哈希。这是ruby中的语法糖。您也可以将此行写入wins = { :rock => :scissors, :scissors => :paper, :paper => :rock}
。
以:
开头的名称在ruby中称为Symbol。符号对象表示常量名称和Ruby解释器中的一些字符串。
第二行{true => p1, false => p2}
的第一部分也是哈希。并且wins[p1] == p2
的值可以根据第一行计算。例如,如果您使用winner(:paper, :rock)
调用此方法,wins[p1]
现在为:rock
,wins[p1] == p2
应为true
。因此{true => p1, false => p2}[true]
是p1
。
ruby中方法的返回值是最后一个表达式的值。