From: 7stud -- Date: 2011-03-02T04:53:16+09:00 Subject: Re: why is $1 in a grep() equal to nil? Robert Klemme wrote in post #984624: > On Fri, Feb 25, 2011 at 9:53 PM, 7stud -- > wrote: >>> worry >>> meth_a >> Uh oh. Someone is going to have to explain that to me. $1 does not act >> like a regular global variable: > > $1, $2 etc. look like global variables but they are in fact local to > the scope where they are set. Thanks for the response Robert. As far as I can tell, there is a difference between $1 and a local variable. Take a look at this example: def test procs = [] %w[a b c].each do |letter| letter =~ /(.)/ #sets value of $1 name = letter #sets value of 'name' my_proc = Proc.new do puts "name = #{name}" puts "$1 = #{$1}" end procs << my_proc end puts "$1 = #{$1}" #puts "name = #{name}" #error: undefined variable or method 'name' return procs end arr = test arr.each do |a_proc| a_proc.call end --output:-- $1 = c name = a $1 = c name = b $1 = c name = c $1 = c The output shows that in all the procs, the value of $1 is the value produced by the last regex match. Yet a new name variable is created every time through the each loop, and each proc closes over a different name variable. So there is a difference between a local variable like name and $1. -- Posted via http://www.ruby-forum.com/.