Wednesday, June 27, 2007

notes of ruby

Similarly, both or and || evaluate to true if either operand is true. They evaluate their
second operand only if the first is false. As with and, the only difference between or
and || is their precedence.
Just to make life interesting, and and or have the same precedence, and && has a higher
precedence than ||.

So how do the $-variables fit in? Well, after every pattern match, Ruby stores a refer-
ence to the result (nil or a MatchData object) in a thread-local variable (accessible
using $~). All the other regular expression variables are then derived from this object.
Although we can’t really think of a use for the following code, it demonstrates that all
the other MatchData-related $-variables are indeed slaved off the value in $~.
re = /(\d+):(\d+)/
md1 = re.match("Time: 12:34am")
md2 = re.match("Time: 10:30pm")
[ $1, $2 ] # last successful match → ["10", "30"]
$~ = md1
[ $1, $2 ] # previous successful match → ["12", "34"]

No comments :