微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby:方法中是否可以有一个heredoc?

如何解决Ruby:方法中是否可以有一个heredoc?

我想在方法中放置一个 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

解决方法

一个字符修正:~

搜索“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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。