From: Eric Christopherson Date: 2011-02-25T11:45:52+09:00 Subject: Re: why is $1 in a grep() equal to nil? On Thu, Feb 24, 2011 at 8:04 PM, 7stud -- wrote: > Eric Christopherson wrote in post #983739: >> On Thu, Feb 24, 2011 at 2:59 PM, 7stud -- >> wrote: >>>  end >>> ---get_cpu_info--- >>>      puts "-->#{$1}<---" >>>        end >>> comp1 = Computer.new(1, DataSource.new) >>> puts comp1.mouse >>> >>> >>> --output:-- >>> Line 32:in `+': can't convert nil into String (TypeError) >>> from t.rb:32:in `mouse' >>> from t.rb:52 >> >> I'm not sure of the specifics, but $1 doesn't persist outside of the >> block created in the grep statement. When you call comp1.mouse, that's >> no longer within that block -- the method was defined in it, but once >> it was made a method it took on an existence of its own. > > $1 is a *global* variable, so saying it doesn't persist outside of a > block doesn't make any sense. > > I think what is happening is that the body of the define_method() call > forms a closure around the variable $1. Oh, I think you have it exactly. I was thinking that maybe the numbered globals weren't truly global, since I read on http://www.rubyist.net/~slagell/ruby/globalvars.html that $_ and $~ aren't actually global.