The two versions are different from each other, since the variable $1 is a local-local and local-method-method. In the first example, $1 exists only in a block outside the hello method. In the second example, $1 exists inside the hello method.
It is not possible to pass $ 1 to the gsub block outside the method definition.
Note that gsub passes the matching string to the block, so z = proc { |m| pp m } z = proc { |m| pp m } will only work as long as your regular expression contains only a complete match. Once your regular expression contains anything other than the link you need, you're out of luck.
For example, "hello".gsub(/l(o)/) { |m| m } "hello".gsub(/l(o)/) { |m| m } => hello , because the entire match string was passed to the block.
Whereas "hello".gsub(/l(o)/) { |m| $1 } "hello".gsub(/l(o)/) { |m| $1 } => helo , since the matched l discarded by the block, all we are interested in is the captured o .
My solution is to match regex, then pass the MatchData object to the block:
require 'pp' def hello(z) string = "hello" regex = /(o)/ m = string.match(regex) string.gsub(regex, z.call(m)) end z = proc { |m| pp m[1] } pp hello(z)
Bryan Ash Aug 31 '13 at 17:41 2013-08-31 17:41
source share