D
Dominik Bathon
First of all, this is no attempt to rival with James' nice Ruby Quiz ;-)
I came up with a nice new(?) use for method_missing today.
Now it is your job to figure out what you can do with it.
(My hope is that someone will find nice uses for this, that I didn't think
of)
So here is the code:
class Array
def method_missing(meth, *args, &block)
rmeth = (meth.to_s =~ /\A_x_(.*)/ ? $1.to_sym : meth)
if block
if empty?
[]
else
mm_block_rec(rmeth, 0, res=[], [], *args, &block)
res
end
else
res=[]
each_with_index { |el, i|
res << el.send(rmeth, *(args.collect { |el|
(Array === el) ? el : el
}))
}
res
end
end
private
def mm_block_rec(rmeth, i, res, bargs, *args, &block)
myargs=args.collect { |el| (Array === el) ? el : el }
res = self.send(rmeth, *myargs) { |*ba|
bargs=(ba.size==1 ? ba.first : ba)
if i==size-1
block.call(*bargs)
else
mm_block_rec(rmeth, i+1, res, bargs, *args, &block)
end
}
end
end
And some questions:
What does it do?
What can it be used for?
Has this been done before? (I couldn't find anything.)
Do you like it?
Dominik
I came up with a nice new(?) use for method_missing today.
Now it is your job to figure out what you can do with it.
(My hope is that someone will find nice uses for this, that I didn't think
of)
So here is the code:
class Array
def method_missing(meth, *args, &block)
rmeth = (meth.to_s =~ /\A_x_(.*)/ ? $1.to_sym : meth)
if block
if empty?
[]
else
mm_block_rec(rmeth, 0, res=[], [], *args, &block)
res
end
else
res=[]
each_with_index { |el, i|
res << el.send(rmeth, *(args.collect { |el|
(Array === el) ? el : el
}))
}
res
end
end
private
def mm_block_rec(rmeth, i, res, bargs, *args, &block)
myargs=args.collect { |el| (Array === el) ? el : el }
res = self.send(rmeth, *myargs) { |*ba|
bargs=(ba.size==1 ? ba.first : ba)
if i==size-1
block.call(*bargs)
else
mm_block_rec(rmeth, i+1, res, bargs, *args, &block)
end
}
end
end
And some questions:
What does it do?
What can it be used for?
Has this been done before? (I couldn't find anything.)
Do you like it?
Dominik