【问题标题】:The "end" statement in RubyRuby 中的“结束”语句
【发布时间】:2016-12-14 17:15:09
【问题描述】:

我有一个 ifelseelse if 语句,我正在使用 Ruby 的官方文档,但我不知道在哪里放置我的 end 语句。

代码如下:

class Menu
  def principal_menu
    user_input = gets
    #On supprime le \n du retour à la ligne
    user_input = user_input.chomp
    if user_input == "3"
      exit
    else if user_input == "1"
      if File.exists?("accounts.txt")
    else 
      File::new("accounts.txt","w+")
    end

    else if user_input == "2"
      new_account = account.new
    end
  end
end

错误是:AccountManager.rb:63: syntax error, unexpected end-of-input, expecting keyword_end

注意:第 63 行是文件的最后。

有人可以帮助 Ruby 的新手吗:D

谢谢!

【问题讨论】:

  • 在 ruby​​ 中,else ifelsif
  • 这里有一个专业提示:正确缩进代码。更好的是,使用具有自动重新格式化功能的编辑器。当您的代码格式正确时,许多语法错误会变得非常明显。
  • Not 如果您不希望默认情况下发生任何事情。 @CarySwoveland
  • @Sergio,我知道。我的评论本来是笼统的,但表述得不好,所以我把它删除了。
  • 我知道缩进,问题是我一直在使用这个文件进行许多测试,最后,它就像一团糟,我知道我不应该这样做,但是.. 嘿,你知道...还是谢谢! (使用记事本++)

标签: ruby if-statement


【解决方案1】:

这是你的问题:

class Menu
    def principal_menu
        user_input = gets
        #On supprime le \n du retour à la ligne
        user_input = user_input.chomp
        if user_input == "3"
            exit
        else if user_input == "1"
            if File.exists?("accounts.txt")
                # you aren't doing anything here
            else 
                File::new("accounts.txt","w+")
            end
        else if user_input == "2"
            new_account = account.new
        end
    end
end

在 Ruby 中,您使用 elsif 而不是 else if。这可能会难倒 Ruby 新手。

这是正确的:

class Menu
    def principal_menu
        user_input = gets
        #On supprime le \n du retour à la ligne
        user_input = user_input.chomp
        if user_input == "3"
            exit
        elsif user_input == "1"
            if File.exists?("accounts.txt")

            else 
                File::new("accounts.txt","w+")
            end

        else user_input == "2"
            new_account = account.new
        end
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多