【问题标题】:Ruby: Is it possible to have a heredoc inside a method?Ruby:方法中是否可以有一个heredoc?
【发布时间】:2021-09-03 04:10:40
【问题描述】:

我想在方法中放置一个heredoc,以便在调用该方法时显示为cli工具的帮助消息。但是,我不断收到“在 EOF 之前的任何地方都找不到字符串 'error_string'”。

我认为这是因为它在方法内部,在类内部,并且终止符需要自己的行,而在方法/类内部缩进时不需要。最好我希望在方法或最坏的类中定义帮助消息,这是可能的还是在文件中的所有其他内容(作为全局变量)之外定义它并在方法中调用它的唯一方法?

为简洁起见,我的代码如下。

class TodoTool

  def help
    puts <<USAGE
    Usage:
    - Create log: todo_list create <task log title> <task title> <task content>
    - View logs and tasks: todo_list view
    - Add task: todo_list add <log to add to> <task title to add> <task content to add>
    - Remove task: todo_list remove <log to remove from> <task to remove>
    USAGE
  end

end

【问题讨论】:

    标签: ruby class methods syntax heredoc


    【解决方案1】:

    一个字符修复:~

    搜索“squiggly heredoc”了解更多信息,或阅读docs。它会删除开头的空格,并允许终止符在其前面有空格。

    class TodoTool
    
      def help
        puts <<~USAGE
        Usage:
        - Create log: todo_list create <task log title> <task title> <task content>
        - View logs and tasks: todo_list view
        - Add task: todo_list add <log to add to> <task title to add> <task content to add>
        - Remove task: todo_list remove <log to remove from> <task to remove>
        USAGE
      end
    
    end
    

    【讨论】:

    • 啊,我明白了!老实说,在阅读文档时,我认为波浪线所指的空格是在heredoc 的正文中,而不是终结符。显然我误解了那一点。谢谢。
    • @Sterling 和&lt;&lt; 终止符必须在行首,&lt;&lt;- 终止符可以缩进,&lt;&lt;~ 内容将被另外剥离。 (相对于缩进最少的行)
    猜你喜欢
    • 2016-11-18
    • 2016-03-18
    • 2011-05-07
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多