Trans
3/19/2006 6:29:00 AM
So here's the Functor class:
class Functor < BasicObject
def initialize(*obj, &func)
@obj = obj
@func = func
end
def method_missing(op, *args)
if @obj.empty?
@func.call(op, *args)
else
@func.call(op, *(@obj + args))
end
end
end
Anyone who has seen the older version of this cllas will notice that I
have added the *obj parameter. This allows the Functor to act like a
simple delegator too. But strictly speaking it isn't at all necessary
since one could just use the object(s) passed to the initialize
directly in the block. Eg.
foo = 1
Functor.new(foo) { |op, obj, *args| obj.send(op, *args) }
is the exact same as
foo = 1
Functor.new { |op, *args| foo.send(op, *args) }
The only time this really is a little more handy is when passing
'self', because of the ambiguity between contexts. Eg.
Functor.new(self) { |op, obj, *args| obj.send(op, *args) }
vs.
slf = self
Functor.new { |op, *args| slf.send(op, *args) }
Not a big deal but there it is. Is there any other reason anyone can
think of that the *obj parameter is acctually needed or more convenient
vs. direct reference in the block itself? If not, is it worth keeping,
or should I just get rid of the *obj parameter altogether?
Settling that issue, I'd like to request that the Functor class be made
part of Ruby's standard library. It is simple, generic and generally
useful --I have had use for it myself on more than a few occasions now
across multiple projects.
Thanks,
T.