Home > Software engineering >  zip more than 2 variables in Ruby
zip more than 2 variables in Ruby

Time:09-21

I am trying to zip 3 variables as I loop on 3 different arrays but the data types are distorted, even though I can print the variables and they are the same, just that they end up being arrays or other data types... (If I print l1 instead of l1.class, I get the right output)

a = [1,2,3]
b = [1,2,3]
c = ['a','b','c']

then

a.zip(b).each do |l1,l2|
  puts l1.class, l2.class
end

gives:

Integer
Integer
Integer
Integer
Integer
Integer

Great! BUT

a.zip(b).zip(c).each do |l1,l2,l3|
  puts l1.class, l2.class, l3.class
end

gives

Array
String
NilClass
Array
String
NilClass
Array
String
NilClass

How do I zip the 3 variables, keeping their types?

Thank you!

CodePudding user response:

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

shows the problem. See Array#zip.

Here are three ways you can obtain the desired result. All print

Integer
Integer
String
Integer
Integer
String
Integer
Integer
String
a.zip(b,c).each { |arr| puts *arr.map(&:class) }

Note

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

If the splat operator (*) were removed the following would be printed:

[Integer, Integer, String]
[Integer, Integer, String]
[Integer, Integer, String]

a.each_index { |i| puts a[i].class, b[i].class, c[i].class }
  #=> [1,2,3]

[a.map(&:class), b.map(&:class), c.map(&:class)]
  .transpose
  .each { |r| puts *r }
  #=> [[Integer, Integer, String],
  #    [Integer, Integer, String], 
  #    [Integer, Integer, String]] 
  •  Tags:  
  • ruby
  • Related