2

This bit of code is taken from Ryan Bates' Railscast episode 343 on full-text search in PostgreSQL. I would like to understand it, but I can't find anything on the <<- operator (if it even is an operator). Can someone please point me to somewhere I can learn about this?

rank = <<-RANK
  ts_rank(to_tsvector(name), plainto_tsquery(#{sanitize(query)})) +
  ts_rank(to_tsvector(content), plainto_tsquery(#{sanitize(query)}))
RANK
user2864740
  • 60,010
  • 15
  • 145
  • 220
Bazley
  • 2,699
  • 5
  • 36
  • 61
  • See [Here-documents](http://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents). My answer would only be a copy/format of the information in the link. – user2864740 May 04 '15 at 00:44

2 Answers2

5

It is a multiline String in ruby, the contents are interpolated and then executed in PostgreSQL. This is a standard way to run scripts on the command line. I use it to write AWS Scripts from within Capistrano.

It uses the here-doc syntax.

http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html

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

aarti
  • 2,815
  • 1
  • 23
  • 31
  • 1
    I didn't know it was called here-doc, I use it all the time in my scripts. thanks for explaining the history http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html – aarti May 04 '15 at 00:47
  • 1
    Also: http://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents – user2864740 May 04 '15 at 00:48
2

It's official name is a heredoc and there are two different ways you can use them. One is how you have it laid out where the start will be <<-NAME and the end will simple be NAME.

The other way you can do it is <<NAME but when closing you have to make sure there are no spaces before NAME on the line. Some example code below to show the difference.

def sample_method
    heredoc1 = <<-NAME
        This is a sample heredoc
    NAME

    heredoc2 = <<OTHERHEREDOC
        Both of these are the same thing
OTHERHEREDOC
end

Both of these will work as heredocs, but as you can see the second one looks a little uglier. Choose whichever you prefer when using them yourself, but make sure to pay attention to white space and the end of string delimiter if you don't include the dash.

tykowale
  • 449
  • 3
  • 13