def winner(p1, p2)
wins = {rock: :scissors, scissors: :paper, paper: :rock}
{true => p1, false => p2}[wins[p1] == p2]
end
问问题
98 次
2 回答
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
于 2012-10-09T09:33:50.570 回答
1
如您所见,这是一个剪刀石头布游戏。def
关键字开始一个方法定义。并且end
意味着方法的结束。
方法主体的第一行wins = {rock: :scissors, scissors: :paper, paper: :rock}
定义了一个名为wins
. 这是 ruby 中的语法糖。您也可以将此行写入wins = { :rock => :scissors, :scissors => :paper, :paper => :rock}
.
以 a 开头的名称:
在 ruby 中称为 Symbol。Symbol 对象表示 Ruby 解释器中的常量名称和一些字符串。
第二行的第一部分{true => p1, false => p2}
也是一个哈希。并且wins[p1] == p2
可以根据第一行计算出的值。例如,如果您使用winner(:paper, :rock)
, wins[p1]
is :rock
now 和wins[p1] == p2
should be调用此方法true
。{true => p1, false => p2}[true]
也是如此p1
。
ruby 中方法的返回值是最后一个表达式的值。
于 2012-10-09T09:36:34.647 回答