作者:Z-19932502872833 | 来源:互联网 | 2023-09-08 20:14
我想在方法中放置一个heredoc,以便在调用该方法时将其显示为cli工具的帮助消息。但是,我不断收到“在EOF之前的任何地方都找不到字符串error_string”的消息
我想在方法中放置一个 heredoc,以便在调用该方法时将其显示为 cli 工具的帮助消息。但是,我不断收到“在 EOF 之前的任何地方都找不到字符串 'error_string'”的消息。
我认为这是因为它在方法内部,在类内部,并且终止符需要自己的行,而在方法/类中缩进时则不需要。最好我希望在方法或最坏的类中定义帮助消息,这是可能的还是唯一的方法来在文件中的其他所有内容之外定义它(作为全局变量)并在方法中调用它?
为简洁起见,我的代码如下。
class TodoTool
def help
puts < Usage:
- Create log: todo_list create
- View logs and tasks: todo_list view
- Add task: todo_list add
- Remove task: todo_list remove
USAGE
end
end
回答
一个字符修复: ~
搜索“squiggly heredoc”以获取更多信息,或阅读文档。它删除开头的空格并允许终止符前面有空格。
class TodoTool
def help
puts <<~USAGE
Usage:
- Create log: todo_list create
- View logs and tasks: todo_list view
- Add task: todo_list add
- Remove task: todo_list remove
USAGE
end
end
@Sterling with `<<` the terminator must be at the very beginning of the line, with `<<-` the terminator can be indented and with `<<~` the content will be stripped in addition. (with respect to the least indented line)