Ruby: <<- operator

227 views Asked by At

I'm working on Rails. In my code base, I see a line that using Arel::SqlLiteral like this:

result = Arel::Nodes::SqlLiteral.new(<<-SQL
  CASE WHEN condition1 THEN calculation1
  WHEN condition2 THEN calculation2
  WHEN condition3 THEN calculation3
  ELSE default_calculation END
SQL)

I understand what this code piece do. The thing I don't understand is its grammar, at this point:

Arel::Nodes::SqlLiteral.new(<<-SQL
  ...
  SQL
)

So in ruby, what is the grammar of <<- follow by name, and then at last block we call that name.

thanks

1

There are 1 answers

1
m0gg On BEST ANSWER

The keyword you're looking for is "Heredoc".

https://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents

It's mainly used to prettify large texts and common practice for shells/shellscripts. The marker on top indicates the beginning of a heredoc and the marker on bottom (which must not be indented unless you place a “-” before the opening marker) specifies the end.