I’m trying to make the following code works but I don’t know how…
···
def mygrep( exp )
ar = [ “element1”, “element2” ]
ar.grep( exp ) { |e|
# works…
print "grep: #$&\n"
yield e
}
end
mygrep( /(.*)/ ) { |e|
doesn’t work…
print “mygrep: #$&\n”
}
Displaying $& in the inner loop of grep works fine, but when it enter my own
block, $& is put back to nil. Is there a way to keep the value of $& (and
all others $1…)?
Displaying $& in the inner loop of grep works fine, but when it enter my own
block, $& is put back to nil. Is there a way to keep the value of $& (and
all others $1...)?
Well, $~ is a local, and thread local variable and perhaps in your case it
best to give this variable to the block, something like
def mygrep( exp )
ar = [ "element1", "element2" ]
ar.grep( exp ) { |e|
yield e, $~
}
end
------------------------------------------------------------------------
class: MatchData
------------------------------------------------------------------------
MatchData is the type of the special variable $~, and is the type
of the object returned by Regexp#match and Regexp#last_match. It
encapsulates all the results of a pattern match, results normally
accessed through the special variables $&, $', $`, $1, $2, and so
on.
Displaying $& in the inner loop of grep works fine, but when it enter my own
block, $& is put back to nil. Is there a way to keep the value of $& (and
all others $1…)?
Well, $~ is a local, and thread local variable and perhaps in your case it
best to give this variable to the block, something like
You can assign a MatchData to $~ and use $& and so on, but I
don’t recommend it.