Thanks for the reply.
I have another related question. To make a parametrized function
creator, I first tried something like:
class Adder < Proc
def initialize(n)
@n = n
end
def call(x)
x+@n
end
end
This broke since Proc expects a block on initialization, so you can't
just do:
add2 = Adder.new(2)
For a simple function like this I was able to instead do:
def mkadder(n); proc {|x| x+n}; end
add2 = mkadder(2)
However, for more complicated procedures it would be nice to be able
to have a real class and methods to encapsulate subprocedures into.
I currently have another potential solution as:
module Callable
def [](x)
call(x)
end
end
class Adder
include Callable
def initialize(n)
@n = n
end
def call(x)
x+@n
end
end
But this seems like a bit of a hack; is there a "right" way to do this
kind of thing?
Thanks again,
daishi
From: Dave Thomas <Dave / PragmaticProgrammer.com>
Subject: Re: [ruby-talk:15633] Q: Function modification/Procedures
Date: 23 May 2001 18:49:20 -0500
> You can use '[]' as an alias for call, so something like
>
> def some_fn(n)
> n * 2
> end
>
> def wrap(&fn)
> proc {|x| some_fn(fn[x])}
> end
>
>
> add_3_times_2 = wrap {|x| x + 3}
>
> add_3_times_2[4] #=> 14
> add_3_times_2[-2] #=> 2
>
>
> I'm not sure if there's a parsing reason that you can't overload '()'.
>
>
> Dave
>