From: Eric Christopherson Date: 2011-02-26T11:06:51+09:00 Subject: Re: why is $1 in a grep() equal to nil? On Fri, Feb 25, 2011 at 2:53 PM, 7stud -- wrote: > Josh Cheek wrote in post #983791: >> On Thu, Feb 24, 2011 at 8:04 PM, 7stud -- >> wrote: >> >>> >>> $1 is a *global* variable, so saying it doesn't persist outside of a >>> block doesn't make any sense. >>> >>> >> It isn't actually global. I don't know the specifics, but I used to >> worry >> about that too, and found out later it was not necessary. [...] > Uh oh.  Someone is going to have to explain that to me.  $1 does not act > like a regular global variable: This is getting more confusing for me. I altered your original script by adding: ['foo'].grep(/f(.)o/) right before your puts "-->#{$1}<---" (at the end of the definition of initialize). Obviously that grep was successful; but surprisingly, the value of $1 remains 'o' even outside of the invocation of initialize: grep_test.rb:30:in `block (2 levels) in initialize': undefined method `get_o_info' for # (NoMethodError) from grep_test.rb:49:in `
' The whole script: # From question on ruby-talk 2/24/2011 class DataSource def get_cpu_info "cpu8001" end def get_cpu_price 101 end def get_mouse_info "mouse241" end def get_mouse_price 40 end end class Computer def initialize(an_id, data_source) @id = an_id @ds = data_source @ds.methods.grep(/^get_(.+?)_info$/) do puts "-->#{$1}<---" Computer.send(:define_method, $1.to_sym) do puts "****" + $1 + "****" #***NIL NIL NIL NIL info = @ds.send("get_#{$1}_info".to_sym) price = @ds.send("get_#{$1}_price".to_sym) alert = "" if price > 100 alert = "*" end puts "#{alert} #{info} #{price}" end puts "-->#{$1}<---" end ['foo'].grep(/f(.)o/) puts "-->#{$1}<---" end end comp1 = Computer.new(1, DataSource.new) puts "$1: #$1" puts comp1.mouse