# Here is another variation (using Symbol#to_proc)
class Symbol
def to_proc
Proc.new { |obj, *args| obj.send(self, *args) }
end
end
class Array
def c2(a) # parallel collect
(0 .. size - 1).collect {|i| yield self[i], a[i]}
end
def c2op(a,opb)
c2(a,&opb)
end
end
# Use with a following block
p [4,3,2,1].c2([2,2,2,2]) {|a,b| a+b}
# => [6, 5, 4, 3]
# or just send the desired operator as a symbol
a=[4,3,2,1]
b=[2,2,2,2]
p a.c2op(b, :+)
# => [6, 5, 4, 3]
# ... or even re-define addition, subtraction etc.
class Array
def +(b)
self.c2op(b, :+)
end
def -(b)
self.c2op(b,
end
end
a=[4,3,2,1]
b=[2,2,2,2]
p a + b
# => [6, 5, 4, 3]
p a - b
# => [2, 1, 0, -1]
-- Mike Berrow
···
--
Posted via http://www.ruby-forum.com/.