Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling zip on an array with a block always return nil

Tags:

arrays

ruby

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

like image 204
user1432824 Avatar asked Jun 08 '12 23:06

user1432824


People also ask

What is the use of ZIP () in Python?

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.

How to unzip files in 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.

What is unzipping in Python?

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.


1 Answers

No

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]].

like image 163
DigitalRoss Avatar answered Sep 28 '22 03:09

DigitalRoss