On Sun, Feb 09, 2003 at 06:31:39PM +0900, Phil Tomson wrote:
> I guess I'm looking for a function generator (maybe I'm ready for 
> functional programming ;-)

Generating functions for fun and profit :-)

  def doubler(fn)
    proc { fn.call; fn.call }
  end

  proc1 = proc { puts "hello" }
  proc2 = doubler(proc1)
  proc2.call


> Why can't I do:
> 
> #yes there are better ways of achieving the same thing
> # it's a contrived example
> class MyProcGen
>   def initialize(sv=0)
>     @start = sv
>     @p = proc { puts @start; @start += 1 }
>   end
>   attr_reader :p
> end
> 
> mpo = MyProcGen.new
> mpo.p.call
> 
> ?
> ....it doesn't work, mpo.p is nil (Why?)

Stick this in a file 'a.rb', type 'ruby a.rb', and it works for me (at least
under 1.6.8). Actually, it works under irb too:

$ irb
irb(main):001:0> class MyProcGen
irb(main):002:1>   def initialize(sv=0)
irb(main):003:2>     @start = sv
irb(main):004:2>     @p = proc { puts self.inspect; puts @start; @start += 1 }
irb(main):005:2>   end
irb(main):006:1>   attr_reader :p
irb(main):007:1> end
=> nil
irb(main):008:0>    
irb(main):009:0* mpo = MyProcGen.new
=> #<MyProcGen:0x815c5a8 @p=#<Proc:0x815c580>, @start=0>
irb(main):010:0> mpo.p.call
#<MyProcGen:0x815c5a8 @p=#<Proc:0x815c580>, @start=0>
0
=> 1
irb(main):011:0> mpo.p.call
#<MyProcGen:0x815c5a8 @p=#<Proc:0x815c580>, @start=1>
1
=> 2
irb(main):012:0> mpo2 = MyProcGen.new
=> #<MyProcGen:0x8156af4 @p=#<Proc:0x8156acc>, @start=0>
irb(main):013:0> mpo2.p.call
#<MyProcGen:0x8156af4 @p=#<Proc:0x8156acc>, @start=0>
0
=> 1
irb(main):014:0> mpo2.p.call
#<MyProcGen:0x8156af4 @p=#<Proc:0x8156acc>, @start=1>
1
=> 2

Regards,

Brian.