So I was trying to take two arrays a
and b
return a third array such that the nth element of the third array is the sum of the nth elements of arrays a
and b
. I was looking at the #zip
method which interleaves arrays such that if a = [1, 2, 3]
and b = [4, 5, 6]
a.zip(b) = [[1, 4], [2, 5], [3, 6]]
. ruby-doc.org says If a block is given, it is invoked for each output array... While messing around with it, I found something interesting though. If you call zip with a block, it always seems to return nil. Am I doing something wrong here?
c = a.zip(b) { |x| x.reduce(:+) }
returns nil
c = a.zip(b).map { |x| x.reduce(:+) }
returns the desired result
The purpose of zip () is to map the similar index of multiple containers so that they can be used just using as single entity. Syntax : zip (*iterators) Parameters : Python iterables or containers ( list, string etc ) Return Value : Returns a single iterator object, having mapped values from all the. containers.
containers. How to unzip? Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “ * ” operator. There are many possible applications that can be said to be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups.
Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “ * ” operator. There are many possible applications that can be said to be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups.
For better or for worse, that's just how it works. It either returns the result or yields it to the block; it doesn't do both.
By the way, in your example a.zip(b)
is actually [[1, 4], [2, 5], [3, 6]]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With