Robert Klemme wrote in post #984624:
> On Fri, Feb 25, 2011 at 9:53 PM, 7stud -- <bbxx789_05ss / yahoo.com>
> 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/.