From the Programming Ruby book:
In addition, you can substitute the value of any Ruby expression
into a string using the sequence #{ expr }.
Up to about an hour ago, I never doubted this statement. I’ve stumbled
upon the following example which is not accepted by ruby. The following
piece of code works perfectly, as to be expected:
name = “peter"
temp = “name=”” + name + “”"
print “<user #{temp}>”
This prints exactly what I want it to print, namely:
One would expect that substituting the RHS of the assignment to temp for
temp in the third statement, would work as well:
name = “peter"
print “<user #{“name=”” + name + “””}>"
Type this in at the ruby prompt and you’ll soon notice that it gives you
the following prompt and not the expected output as above:
irb(main):003:-1/
Note the -1 in the prompt, meaning ruby managed to get above the toplevel.
Ruby just keeps waiting for input, and I can type anything but ruby will
stay in this state until I type a / and then unhappily states this:
(irb):2: warning: escaped terminator ‘"’ inside string interpolation
SyntaxError: compile error
(irb):3: unterminated string meets end of file
(irb):3: syntax error
from (irb):3
Anyway, what happens is that the escaped quotes are misinterpreted since
the problem is gone when I leave them out. The effect is that the slash in
is interpreted as the start of a regular expression. This can only
be if ruby thinks it’s not part of a string string, which was clearly not
my intention.
Can someone please tell me whether this is a bug, or otherwise why I
shouldn’t have done the above.
Note: I’m using version 1.8.0 of ruby, don’t know if the trueness of the
above statement from Programming Ruby changed as the ruby version changed.
Thanks,
Peter