学习ruby,这些代码片段意味着什么?

时间:2012-10-09 09:18:42

标签: ruby

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"

2 个答案:

答案 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]现在为:rockwins[p1] == p2应为true。因此{true => p1, false => p2}[true]p1

ruby​​中方法的返回值是最后一个表达式的值。