1

At http://janlelis.github.io/ruby-bad-parts/#19 I can notice some strange example of Ruby syntax.

>> a = "Eurucamp #\n"
>> a.gsub /#$//, ''
# => "Eurucamp #"

I'm not Ruby programmer, but I'm wondering why it works, and what it does?

Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
  • 1
    That looks like a regex literal – SLaks Jan 24 '14 at 20:19
  • In addition to the answers below, I'd also note that gsub does not require you to pass a regular expression to it, a string works just fine. Therefore, `a.gsub $/, ''` would work just as well in this case and be more readable. – Ajedi32 Jan 24 '14 at 21:16

1 Answers1

3

As $/ global variable means \n in Ruby.

2.0.0-p0 :001 > a = "Eurucamp #\n"
 => "Eurucamp #\n" 
2.0.0-p0 :002 > a.gsub /#$//, ''
 => "Eurucamp #" 
2.0.0-p0 :003 > $/
 => "\n" 
2.0.0-p0 :004 > /#$//.source
 => "\n" 
2.0.0-p0 :005 > a.gsub /##$//, ''
 => "Eurucamp " 
2.0.0-p0 :006 > /##$//.source
 => "#\n" 

In your Regexp patteren you are telling Stirng#gsub method, that in the source string if you find "\n", replace it with a empty string(''). Using Regexp#source you will always get back the original string of the pattern, so I did use /#$//.source, and found that it is '\n'.

/#$//
 ^^^ <~~~ string interpolation happened, which is a shortcut of #{$\}

See this post Why does this string interpolation work in Ruby? as commented by @rampion.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Just wondering, do you know why regex doesn't match `#` in this case then? – Konrad Borowski Jan 24 '14 at 20:21
  • 2
    Ruby string interpolation is normally `#{...}` except `#@ivar` is shorthand for `#{@ivar}` and `#$gvar` is shorthand for `#{$gvar}` – rampion Jan 24 '14 at 20:43
  • 1
    @xfix: Only global and instances variables in double quoted string contexts, `#{...}` is required for non-global and non-instance variable expressions. This is one of the dumb misfeatures in Ruby that seemed like a good idea at the time but turned out to be not so good. – mu is too short Jan 24 '14 at 20:44
  • @rampion Doing inspections I got to know why that result.. But did not know what you and *muistoshort* mentioned.. Thanks both of you.. Any source where you found this information.. – Arup Rakshit Jan 24 '14 at 20:48
  • @muistooshort You are right - *Only global and instances variables in double quoted string contexts*. But the same is also true in the context of regular expression. – Arup Rakshit Jan 24 '14 at 21:13
  • A regex *is* a *double quoted string context* in that it allows string interpolation, just like `"..."`, `%Q{...}`, `%W[...]`, and heredocs. – mu is too short Jan 24 '14 at 21:45