Is there a nice way to create a Ruby array chainable on the fly that combines map and inject?
Here's what I mean. Let a
be an array of integers, then to get all sums of 2 adjacent elements we can do:
a.each_cons(2).map(&:sum)
We can also get the product of all the elements of an array a
by:
a.inject(1,&:*)
But we can't do:
a.each_cons(2).map(&:inject(1,&:*))
We can, however, define an array chainable:
class Array
def prod
return self.inject(1,&:*)
end
end
Then a.each_cons(2).map(&:prod)
works fine.