Understanding ruby

I found this block of code on Wikipedia as an example of quine (a program that prints itself) in Ruby.

puts <<2*2,2 puts <<2*2,2 2 

However, I do not understand how this works. In particular, I do not understand that when I delete the last line, I get this error:

syntax error, unexpected end of $, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END

What happens on these lines?

+6
source share
2 answers

The syntax <<something starts here — a document borrowed from UNIX shells through Perl is basically a multi-line string literal that starts in the line after << and ends when the line starts with something .

So structurally, the program simply does this:

 puts str*2,2 

... that is, print two copies of str , and then number 2.

But instead of the str variable, it includes a literal string through the document here, the end of which is also the number 2:

 puts <<2*2,2 puts <<2*2,2 2 

Thus, he prints two copies of the line puts <<2*2,2 , followed by 2. (And since the method used to print them puts , each of these things automatically adds a new line.)

+6
source

In ruby ​​you can define strings with

 str = <<DELIMITER long string on several lines DELIMITER 

I suggest that from here you can guess the rest :)

+1
source

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


All Articles