Search code examples
rubyclassmethodssyntaxheredoc

Ruby: Is it possible to have a heredoc inside a method?


I want to put a heredoc inside a method to be displayed as a help message for a cli tool when the method is called. However, I keep getting the "can't find the string 'error_string' anywhere before EOF."

I think this is because it is inside a method, inside a class, and the terminator needs its own line, which it doesn't when it is indented inside a method/class. Preferably I would like to have the help message defined within the method or at worst the class, is this possible or is the only way to define it outside of everything else in the file (as a global variable) and call it in the method?

The code I have is below for brevity.

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

Solution

  • One character fix: ~

    Search for "squiggly heredoc" for more information, or read the docs. It removes the whitespace in the beginning and allows the terminator to have whitespace in front of it.

    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