citizen428.blog()

Try to learn something about everything

Haskell Like "Zip_with" for Ruby

I always liked Haskell’s zipWith and sometimes miss it in Ruby, so I wrote my own a couple of weeks ago. I also submitted a pull request to Facets, but since it’s still not included I decided to post the code here in case it’s useful for anyone:

1
2
3
4
5
6
7
8
9
10
def zip_with(other, op=nil)
  return [] if self.empty? || other.empty?
  clipped = self[0..other.length-1]
  zipped = clipped.zip(other)
  if op
    zipped.map { |a, b| a.send(op, b) }
  else
    zipped.map { |a, b| yield(a,b) }
  end
end

Usage examples:

1
2
[1,2,3].zip_with([6,5,4], :+) #=> [7, 7, 7]
[1,2,3].zip_with([6,5,4]) { |a,b| 3*a+2*b } #=> [15, 16, 17]

Comments