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?
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?
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.