Ruby HEREDOC syntax string interprets

I wanted to do a little regular testing using irb with an HTML page. I am trying to remove something from.

However, the HEREDOC syntax that we all know and love seems to be different from Ruby:

irb(main):140:0> text = <<-FUNUNU <p class="firstpara"> irb(main):141:0" FUNUNU irb(main):142:0* irb(main):143:0* puts text SyntaxError: compile error (irb):140: syntax error, unexpected kCLASS, expecting kDO or '{' or '(' text = <<-FUNUNU <p class="firstpara"> ^ (irb):143: syntax error, unexpected tIDENTIFIER, expecting kDO or '{' or '(' from (irb):143 from :0 

He seems to be complaining about the contents of the string, trying to interpret it. Of all the documentation I could find in the HEREDOC syntax, all indicate that all keywords should be part of a variable. But it doesn’t look like that.

Are there any restrictions on formatting the contents of the string, except that the HEREDOC string ends with the second expression of the HEREDOC indicator?

+6
source share
3 answers

You cannot put a string on the same line of the heredoc separator, because after the separator, it is allowed to put Ruby code on the same line, i.e.

 irb> text = <<-FOO # Ruby code allowed here... irb* <a class="foo"> irb* FOO # => "<a class=\"foo\">\n" irb> text # => "<a class=\"foo\">\n" 

This is because you can write something like this:

 irb> instance_eval(<<-CODE) irb* def foo irb* "foo" irb* end irb* CODE 

Or even:

 def foo(a, b, c) [a, b, c] end foo(<<-A, <<-B, <<-C) foo A bar B baz C # => ["foo\n", "bar\n", "baz\n"] 
+15
source

As already noted, the heredoc text begins on the next line after the heredoc terminator. This is not intended to replace these answers, but rather provides a possible better alternative to the typical heredoc syntax.

I personally prefer using %q{} . This is equivalent to using single quotes. Below are the same results:

 text = %q{ <a class="foo"> } text = ' <a class="foo"> ' 

If you want to use string interpolation:

 text = %Q{ <a class="#{class_name}">} 

You can also disable {} for other terminators. The following two lines give exactly the same result:

 text = %Q[ <a class="#{class_name}">] text = %Q| <a class="#{class_name}">| 

And they support multiple lines:

 text = %q{<p> Some text </p>} 

There are some good answers to this SO question regarding the various uses for this syntax.

+6
source

The first line of heredoc allows you to use an extra ruby. The line starts after the carriage returns.

http://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#here_doc

+2
source

Source: https://habr.com/ru/post/947217/


All Articles