Codepart - please explain!

Hey everyone,

I’ve found a code part that I don’t understand:

def runCode
return <<STARTCODE
(…)
STARTCODE
end

Unfortunately the google search doesn’t work because the << will be
ignored.
Could you explain what it’s doing?

Oh, and I can’t try out what it’s doing because I’ll get the error that
STARTCODE can’t be found until EOF…

Thx

Il giorno Mon, 23 Jan 2012 02:54:17 +0900
Blub B. [email protected] ha scritto:

end

It’s another form of string literal, just as ’ ’ or " ". The string
content
start from the line after STARTCODE and continues until a line starting
with
STARTCODE is found. Note that the line must truly start with STARTCODE,
it
can’t have any leading whitespace (this is the reason you get an error).
If
you want to have whitespace before the closing STARTCODE, you must put a

after the <<:

return <<-STARTCODE

Note that the delimiting string doesn’t need to be STARTCODE, it can be
anything you like, as long as you use the same string at the beginning
and
end of the string.

I hope this helps

Stefano

On Sun, Jan 22, 2012 at 6:54 PM, Blub B. [email protected]
wrote:

end

Unfortunately the google search doesn’t work because the << will be
ignored.
Could you explain what it’s doing?

Oh, and I can’t try out what it’s doing because I’ll get the error that
STARTCODE can’t be found until EOF…

The technique is called a “here doc”.

First match in Google

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

The specific issue in your code example is that you need to use either:

def runCode
return <<STARTCODE
(…)
STARTCODE # NO margin left of STARTCODE
end

or:

def runCode
return <<-STARTCODE
(…)
STARTCODE
end

If you had access to an editor with built-in coloring,
these types of problems become immediately obvious
(like e.g. vim and many others).

HTH,

Peter

On Sun, Jan 22, 2012 at 7:10 PM, Peter V.
[email protected] wrote:

(…)

return <<STARTCODE
(…)
STARTCODE # NO margin left of STARTCODE
end

Careful with comments on that line:

13:33:38 Temp$ ruby19 x.rb
x.rb:6: can’t find string “STARTCODE” anywhere before EOF
x.rb:2: syntax error, unexpected $end, expecting tSTRING_CONTENT or
tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
13:34:12 Temp$ cat -n x.rb
1
2 s=<<STARTCODE
3 x
4 STARTCODE # NO margin left of STARTCODE
5
6 p s
13:34:14 Temp$

Cheers

robert

On Mon, Jan 23, 2012 at 1:35 PM, Robert K.
[email protected]wrote:

On Sun, Jan 22, 2012 at 7:10 PM, Peter V.
[email protected] wrote:

x.rb:2: syntax error, unexpected $end, expecting tSTRING_CONTENT or
Cheers

robert

Indeed.

I did some tests now and if I see correctly, both
the EOS (End Of String) and -EOS here doc formats
require that EOS is immediately followed by a
newline in the code.

Thank you :slight_smile:

Peter

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs