0

我刚刚开始我的 ruby​​ 之旅,而且对编程也很陌生。这是家庭作业的代码。我收到标题中描述的语法错误。我知道我在预期文件结尾时添加了一些额外的结尾?正确的?但是这个额外的“结束”在哪里。

编码:

class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end

def rps_result(move1,move2)

  if (move1 == "r" && move2 == "s") || (move1 == "s" && move2 == p) || (move1 == "p" && move2 == "r")
    return true 
  else 
    return false
  end

结尾

  def rps_game_winner(player1, player2)    
    strategy = /[rps]/
    raise NoSuchStrategyError unless (move1 =~ strategy) & (move2 =~ strategy) 

    move1 = player1[1].downcase
    move2 = player2[2].downcase

    rps_result(move1, move2)? player1 : player2
  end
end

def rps_tournament_winner(game)
  round_winners = []

  if game.length < 2
    raise WrongNumberOfPlayersError
  else
    game.each_slice(2) do
      |l1 , l2|
      round_winners << rps_game_winner(l1, l2)
    end

    rps_tournament_winner(round_winners) 
  end
end

rps_tournament_winner([[[["Richard", "S"], ["Dave", "S"]], [["Richard", "R"], ["Michael", "S"]]], [[["Allen", "S"], ["Omer", "P"]], [["David E.", "R"], ["Richard X.", "P"]]]])
4

2 回答 2

0

rps_result方法永远不会关闭。end将末尾的第二个移动rps_game_winner到方法的最后一个预期行rps_result

Ps 对不起所有end的 :)

于 2013-04-04T06:13:42.273 回答
0

我已经修改了第二个代码块。请检查它是否有效。

def rps_game_winner(player1, player2)    
    strategy = /[rps]/
    raise NoSuchStrategyError unless (move1 =~ strategy) && (move2 =~ strategy) 

    move1 = player1[1].downcase
    move2 = player2[2].downcase

    rps_result(move1, move2) ? player1 : player2
end    

def rps_tournament_winner(game)
  round_winners = []

  if game.length < 2
    raise WrongNumberOfPlayersError
  else
    game.each_slice(2) do |l1 , l2|
      round_winners << rps_game_winner(l1, l2)
    end

    rps_tournament_winner(round_winners) 
  end
end

rps_tournament_winner([[[["Richard", "S"], ["Dave", "S"]], [["Richard", "R"], ["Michael", "S"]]], [[["Allen", "S"], ["Omer", "P"]], [["David E.", "R"], ["Richard X.", "P"]]]])

做了4个改动:

  1. endrps_game_winner方法中删除了额外的内容。

  2. rps_game_winner在方法中的三级运算符之间添加了空格。

  3. rps_game_winner方法,第二行,unless条件只有一个&

  4. 在方法中rps_tournament_winner,将 args 移到.|l1, l2|do

于 2013-04-04T07:02:00.767 回答