On Thu, Feb 24, 2011 at 2:59 PM, 7stud -- <bbxx789_05ss / yahoo.com> wrote:
> class DataSource
> =A0 =A0def get_cpu_info
> =A0 =A0 =A0 =A0"cpu8001"
> =A0 =A0end
> =A0 =A0def get_cpu_price
> =A0 =A0 =A0 =A0101
> =A0 =A0end
>
> =A0 =A0def get_mouse_info
> =A0 =A0 =A0 =A0"mouse241"
> =A0 =A0end
> =A0 =A0def get_mouse_price
> =A0 =A0 =A0 =A040
> =A0 =A0end
> end
>
> DataSource.new.methods.grep(/^get_(.*?)_info$/) do |meth|
> =A0 =A0puts "---#{meth}---"
> end
>
> --output:--
> ---get_cpu_info---
> ---get_mouse_info---
>
>
> class Computer
> =A0 =A0def initialize(an_id, data_source)
> =A0 =A0 =A0 =A0@id =3D an_id
> =A0 =A0 =A0 =A0@ds =3D data_source
>
> =A0 =A0 =A0 =A0 / ds.methods.grep(/^get_(.+?)_info$/) do
>
> =A0 =A0 =A0 =A0 =A0 =A0puts "-->#{$1}<---"
>
> =A0 =A0 =A0 =A0 =A0 =A0Computer.send(:define_method, $1.to_sym) do
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0puts "****" + $1 + "****" =A0 #***NIL NIL =
NIL NIL
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0info =3D @ds.send("get_#{$1}_info".to_sym)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0price =3D @ds.send("get_#{$1}_price".to_sy=
m)
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0alert =3D ""
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0if price > 100
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0alert =3D "*"
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0end
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0puts "#{alert} #{info} #{price}"
> =A0 =A0 =A0 =A0 =A0 =A0 end
> =A0 =A0 =A0 =A0end
> =A0 =A0end
>
> end
>
>
>
> comp1 =3D Computer.new(1, DataSource.new)
> puts comp1.mouse
>
>
> --output:--
> Line 32:in `+': can't convert nil into String (TypeError)
> =A0from t.rb:32:in `mouse'
> =A0from 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.