【问题标题】:Rubywarrior Level 4 (cleaning up my code help)Rubywarrior Level 4(清理我的代码帮助)
【发布时间】:2012-05-14 15:27:03
【问题描述】:

我正在通过 Ruby 学习编程,并且我发现了来自 Railscasts 的 Ryan Bates 写的很棒的 Rubywarrior。不幸的是,我被困在我的代码抛出语法错误消息(意外的 $end)。

我不是在要求答案,我想自己解决这个问题,但如果有人能指出我的代码从哪里得到错误,那就太好了。谢谢!

class Player

  def initialize
    @maxhealth = 20
    @dying = 7
    @previoushealth = @maxhealth
    @health = warrior.health
    @warrior = warrior
  end

  def play_turn(warrior)
  # If there are no enemies, rest until health is 100%
    turn_start_check(warrior)
    actions(warrior)
    turn_end_check(warrior)
  end

  def actions(warrior)
    if @damaged_since_last_turn
      warrior.shoot!
    elsif
      @health < @maxhealth
        warrior.rest!
    else
      warrior.walk!
    end
  end

  def hurt?(warrior)
    warrior.health < 20
  end

  def healthy?(warrior)
    warrior.health = 20
  end

  def alone?(warrior)
    warrior.feel.empty?
  end

  def should_i_move?(warrior)
    if healthy? and alone?
      warrior.rest!
    else
      warrior.walk!
  end

  # Put code here for if health from previous turn is less than last term
  # If true don't rest and keep moving forward
  def turn_start_check(warrior)
    @damaged_since_last_turn = @previoushealth > warrior.health
  end

  def turn_end_check(warrior)
    @previoushealth = warrior.health
  end
end

【问题讨论】:

  • 对于学习 Ruby 的人来说,您的代码看起来非常干净(这很棒!),但您可能会发现将条件与 elsif 中的 actions 放在同一行对您的理智很有用方法。这样结构与您的if 声明相同

标签: ruby code-cleanup


【解决方案1】:

我的猜测:

def should_i_move?(warrior)
  if healthy? and alone?
    warrior.rest!
  else
    warrior.walk!
  end  # <<MISSING THIS ONE
end

【讨论】:

  • 啊,我不想给他答案:)
  • 谢谢!自从我学习了一些 Python 后,我仍然习惯了整个“最终”业务。该死的空格。
  • :-] 这也让我有些困惑 - 我是从 perl 开始使用 ruby​​ 的,所以我希望看到 {}。加上语法错误不是我所期望的。例如,在您的情况下,它说“意外的 $end”而不是“缺失的结尾”。
  • 我不时得到的一个是“意外的结局,期待:”这让我很震惊。
【解决方案2】:

该错误消息意味着您在某处缺少end 关键字。检查您的代码,看看您的所有语句是否都正确编写。

【讨论】:

    【解决方案3】:

    在 Ruby 1.9.3 中,如果您打开警告,您会收到以下警告:

    -:46: warning: mismatched indentations at 'end' with 'if' at 42
    -:57: warning: mismatched indentations at 'end' with 'def' at 41
    

    然后是错误

    -:57: syntax error, unexpected $end, expecting keyword_end
    

    第46行对应def should_i_move?(warrior)之后的第一个end

    这应该也适用于早期版本的 Ruby 1.9。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多