Given the following two pieces of code:
def hello(z)
\"hello\".gsub(/(o)/, &z)
end
z = proc {|m| p $1}
hello(z)
# prints: nil
Things like $1
, $2
acts like LOCAL VARIABLES, despite its leading $
. You can try the code below to prove this:
def foo
/(hell)o/ =~ 'hello'
$1
end
def bar
$1
end
foo #=> "hell"
bar #=> nil
Your problem is because the proc z
is defined outside the method hello
, so z
accesses the $1
in the context of main
, but gsub
sets the $1
in the context of method hello
.