[英]Learning ruby, what do these snippets of code mean?
def winner(p1, p2)
wins = {rock: :scissors, scissors: :paper, paper: :rock}
{true => p1, false => p2}[wins[p1] == p2]
end
From this question: HW impossibility?: "Create a rock paper scissors program in ruby WITHOUT using conditionals" 来自这个问题: 硬件不可能吗?:“不用条件就可以在红宝石中创建剪刀石头布程序”
I admit, this is not the most readable code for a novice programmer. 我承认,对于初学者来说,这不是最易读的代码。 I rewrote it, extracted some variables and added comments.
我重写了它,提取了一些变量并添加了注释。 Hope you can understand it better now.
希望您现在能更好地理解它。
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
This is a rock-scissor-paper game as you can see. 如您所见,这是一个剪刀石头布游戏。 The
def
keyword starts a method definition. def
关键字启动方法定义。 And end
means the end of the method. end
表示方法的结束。
The first line of the method's body wins = {rock: :scissors, scissors: :paper, paper: :rock}
defines a hash called wins
. 方法主体的第一行
wins = {rock: :scissors, scissors: :paper, paper: :rock}
定义了一个称为wins
的哈希。 This is a syntax sugar in ruby. 这是ruby中的语法糖。 You can also write this line into
wins = { :rock => :scissors, :scissors => :paper, :paper => :rock}
. 您也可以将此行写成
wins = { :rock => :scissors, :scissors => :paper, :paper => :rock}
。
Names starting with a :
is called Symbol in ruby. 以
:
开头的名称在红宝石中称为符号。 Symbol objects represent constant names and some strings inside the Ruby interpreter. 符号对象代表常量名称和Ruby解释器中的一些字符串。
The first part of the 2nd line {true => p1, false => p2}
is also a hash. 第二行的第一部分
{true => p1, false => p2}
也是一个哈希。 And the value of wins[p1] == p2
can be calculated according to the first line. 可以根据第一行计算
wins[p1] == p2
的值。 For example, if you call this method with winner(:paper, :rock)
, wins[p1]
is :rock
now and wins[p1] == p2
should be true
. 例如,如果使用
winner(:paper, :rock)
调用此方法,则wins[p1]
现在是:rock
并且wins[p1] == p2
应该为true
。 So {true => p1, false => p2}[true]
is p1
. 因此
{true => p1, false => p2}[true]
是p1
。
The return value of a method in ruby is the value of the last expression. 红宝石中方法的返回值是最后一个表达式的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.