This post originated from an RSS feed registered with Ruby Buzz
by Rick DeNatale.
Original Post: In Ruby Globals, Aren't Always Global
Feed Title: Talk Like A Duck
Feed URL: http://talklikeaduck.denhaven2.com/articles.atom
Feed Description: Musings on Ruby, Rails, and other topics by an experienced object technologist.
The idea is to introduce a special variable called it, which holds the result of the conditional expression in an if or unless statement, or method in Ioke’s case. Ola says that this is different from the special Ruby globals like $~ because For one, it’s not a global variable. It’s only available inside the lexical context if an ‘if’ or ‘unless’ method. It’s also a lexical variable, meaning it can be captured by a closure. And finally, it’s a general solution to more things than the regular expression problem.
As it turns out, I learned at RubyConf that the Ruby ‘globals’ which give access to the results of the last regular expression match, aren’t really globals at all. This came up in a conversation after the MagLev presentation, when Charlie Nutter asked Allen Otis of Gemstone how they were handling those variables, since they are really frame locals. Matz was standing there and quickly confirmed Charlies observation.
So $~ and it’s friends, like $1, are really more like special names for local variables. Other than the lexical ‘look’ they behave more like locals than globals.
I just concocted a completely bogus Ruby program to demonstrate this.
def lambdas(str, re)
re.match(str)
[lambda {$~}, lambda {|str| re.match(str)}]
end
m_lambda, match_lambda = *lambdas("this", /(this|that)/)
puts "(m_lambda.call)[1] is #{(m_lambda.call)[1].inspect}"
/(foo)/.match("foo")
puts "$~[1] is #{$~[1].inspect}"
puts "m_lambda still is #{(m_lambda.call)[1].inspect}"
match_lambda.call('that')
puts "now m_lambda is #{(m_lambda.call)[1].inspect}"
puts "$~[1] is still #{$~[1].inspect}"
The lambdas method returns two lambdas, the first simply returns the current value of $~ when evaluated, the second does
a match against the regular expression passed into the lambdas method with a new string, on demand.
When run this produces the following output:
(m_lambda.call)[1] is "this"
$~[1] is "foo"
m_lambda still is "this"
now m_lambda is "that"
$~[1] is still "foo"
Note that $~ in the outer context is a different variable than $~ in the context of the invocation of the lambdas method.
Let’s call these the outer and inner $~ variables respectively.
Doing a regular expression match in the outer context leaves the inner $~ unchanged, while calling the second lambda affects the value of the inner $~ but leaves the outer $~ unchanged.