1

I am browsing through the ruby Array iterators. And I can't find what I am looking for and I think it already exists:

I have two arrays:

["a", "b", "c"]

[0,1,2]

And I want to merge as so:

[ [0, "a"], [1, "b"], [2, "c"] ]

I think the iterator exists in the standard library (I used it before) but I am having trouble finding its name.

Daniel Viglione
  • 8,014
  • 9
  • 67
  • 101

3 Answers3

4

This should work:

[0,1,2].zip(["a", "b", "c"])        # => [[0, "a"], [1, "b"], [2, "c"]]

From the official documentation of the Array#zip function:

Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.

This generates a sequence of ary.size n-element arrays, where n is one more than the count of arguments.

For more info and some other examples, refer to:

https://ruby-doc.org/core-2.4.2/Array.html#method-i-zip

Community
  • 1
  • 1
Doodad
  • 1,518
  • 1
  • 15
  • 20
0

You are looking for the zip function

https://apidock.com/ruby/Array/zip

sakurashinken
  • 3,940
  • 8
  • 34
  • 67
0

I think you could use https://apidock.com/ruby/Enumerator/each_with_index See this post difference between each.with_index and each_with_index in Ruby?

or if you have specific values and you want to map them you would use map or zip. It explains it well in this post Combine two Arrays into Hash

Laurie
  • 162
  • 1
  • 11