Documenting string

Hi everyone,

Below is a short and functioning program:
#!/usr/bin/ruby

def call_me
e = <<SOME

this is a nice string!

SOME
e
end

puts call_me
It runs and displays string between SOME delimiters.
My question is why, if I add to first # (between SOME delim), like this

#!/usr/bin/ruby

def call_me
e = <<SOME
#@

this is a nice string!

SOME
e
end

puts call_me

I got this error, in line with #@ sign:
syntax error, unexpected $undefined

Does #@ sign have a special meaning in ruby?

I believe Ruby treats this as a double quoted string. The following
seems to confirm that.

irb(main):001:0> @cow = “bessie”
=> “bessie”
irb(main):002:0> e = <<SOME
irb(main):003:0" #
irb(main):004:0" # moo
irb(main):005:0" #
irb(main):006:0" SOME
=> “#\n# moo\n#\n”
irb(main):007:0> e
=> “#\n# moo\n#\n”
irb(main):008:0> e = <<SOME
irb(main):009:0" #
irb(main):010:0" #@cow
irb(main):011:0" #
irb(main):012:0" SOME
=> “#\nbessie\n#\n”

Looks like Ruby’s sees the start of an instance variable when it hits
the “@”.

Oh, indeed “instance variable”!!
and #@something inside doc string it sees live “#{@something}”!!!
Thank you very much, Bob, now understand!

Ciur Eugen wrote:

Oh, indeed “instance variable”!!
and #@something inside doc string it sees live “#{@something}”!!!
Thank you very much, Bob, now understand!

And incidentally, you can change the semantics of heredocs to those of
single-quoted strings by single-quoting the terminator. e.g.

def call_me
e = <<‘SOME’
#@

this is a nice string!

SOME
e
end

puts call_me

(But this won’t let you embed #{…} interpolation in your string
either)

Thank you Brian, that is really what I was looking for !

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