3

Please observe the following:

"abcd#fg"  # => "abcd#fg"
"abcd#$fg" # => "abcd"    characters #$ and after them are skipped
"abcd#@fg" # => "abcd"    characters #@ and after them are skipped

It could be string interpolation just with # instead of #{}.

$fg = 8
"abcd#$fg" # => "abcd8" 
@fg = 6
"abcd#@fg" # => "abcd6" 

It works like interpolation. Is it a bug or a feature?

sawa
  • 165,429
  • 45
  • 277
  • 381
Virtual
  • 2,111
  • 5
  • 17
  • 27
  • @toro2k, Thanks. I didn't notice that question. – Virtual Mar 12 '14 at 09:25
  • Of course it is a feature. It is really a bad habit of beginners to so easily attribute to someone else's bug something they don't understand. I really wonder why beginners tend to think that they are correct and the software is wrong. Experienced programmers are more modest. – sawa Mar 12 '14 at 09:31
  • 1
    @sawa I don't think this is such an unreasonable question. – Wayne Conrad Mar 12 '14 at 09:50
  • @WayneConrad If it asked why such thing happens, then it is not unreasonable to ask. What is unreasonable is to suspect a bug so easily. – sawa Mar 12 '14 at 10:05

1 Answers1

7

You can actually interpolate global, instance, and class variables omitting the braces:

$world = 'world'
puts "hello, #$world"
# hello, world

In your example both $fg and @fg are uninitialized and thus evaluated to nil, that's why they are intorpolated as empty strings. When you write "abcd#fg" nothing is interpolated because the # is not followed by one of {, @, $.

You can find the feature documented in the RubySpec (thanks to @DavidMiani).

If you ask me, don't rely on this behaviour and always interpolate variables using braces, both for readability and to avoid problems such:

@variable = 'foo'
puts "#@variable_bar"

This will output an empty string instead of the, probably, expected string "foo_bar", because it is trying to interpolate the undefined instance variable @variable_bar.

toro2k
  • 19,020
  • 7
  • 64
  • 71
  • 2
    It is present in the [ruby spec string file](https://github.com/rubyspec/rubyspec/blob/master/language/string_spec.rb) though, so any ruby that passes that spec will work with that syntax. – David Miani Mar 12 '14 at 09:34
  • The links to RubySpec are dead. I only found that RubySpecs is closed. https://github.com/rubyspec/rubyspec/ – Mauddev Jun 26 '15 at 21:25