语法错误,意外的keyword_end,期待$ end

时间:2013-04-04 06:06:47

标签: ruby syntax-error

我刚刚开始我的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"]]]])

2 个答案:

答案 0 :(得分:0)

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

P.S。抱歉所有的end:)

答案 1 :(得分: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. end方法中删除了额外的rps_game_winner

  2. rps_game_winner方法中增加了第三级运算符之间的空间。

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

  4. rps_tournament_winner方法中,在|l1, l2|之后移动了do