when I run this snippet,
puts “I’m the #{$0} script.”
I can see the output like,
I’m the exercise.rb script.
Here, I realized that “#{$0}” interpolated the exercise.rb into the
String.
How does it happened?
I see only empty string while using “#{$1}”.
Selvag R. wrote in post #1143349:
when I run this snippet,
puts “I’m the #{$0} script.”
I can see the output like,
I’m the exercise.rb script.
Here, I realized that “#{$0}” interpolated the exercise.rb into the
String.
How does it happened?
I see only empty string while using “#{$1}”.
Well, it’s different than with shell scripts: $1 stores the first
capturing group of a regex match. If you want script arguments you’ll
have to look in ARGV. For some applications also ARGF is useful.
Btw. with global variables you can even do this:
puts “I’m the #$0 script.”
Kind regards
robert
You will not see value in $1 until you have matched some Regexp.
And to answer why it happens: when you use double quotes, code inside
#{} is parsed and the result is converted to string. So if $1 is nil,
then nil.to_s == ‘’ .
Damián M. González wrote in post #1143363:
You will not see value in $1 until you have matched some Regexp.
And to answer why it happens: when you use double quotes, code inside
#{} is parsed and the result is converted to string. So if $1 is nil,
then nil.to_s == ‘’ .
So, How does “#{$0}” shows current file name?
$0 is defined by the interpreter when Ruby starts. It is one of the
handy “predefined global variables” put there to make Ruby programming
simpler.
It is not related Regexp like $1, $2, etc.
Joel P. wrote in post #1143803:
$0 is defined by the interpreter when Ruby starts. It is one of the
handy “predefined global variables” put there to make Ruby programming
simpler.
It is not related Regexp like $1, $2, etc.
Thank you, I understood.