Maybe someone could help me with this. I have an array of arrays. The internal arrays have different sizes (from 2 to 4 elements).
letters = [["A", "B"],["C", "D", "F", "G"],["H", "I", "J" ]]
I'm trying to print in a same line each array havins as first column element[0] and element[1] joined, as 2nd column element[0], element[1], element[2] joined as 3rd column element[0], element[1], element[3] joined. Elements 2 and 3 not always exist.
The output I'm trying to get is like this:
AB
CD CDF CDG
HI HIJ
I'm doing in this way but I'm getting this error.
letters.map{|x| puts x[0]+x[1] + "," + x[0]+x[1]+x[2] + "," + x[0]+x[1]+x[3]}
TypeError: no implicit conversion of nil into String
from (irb):1915:in "+"
from (irb):1915:in "block in irb_binding"
from (irb):1915:in "map"
from (irb):1915
from /usr/bin/irb:11:in "<main>"
prints
The steps are as follows.
Suppose
Then
The first element of this enumerator is generated and passed to the block, and the three block variables are assigned values.
Next, we obtain
The first element of this enumerator is generated and passed to the block, and the block variables are assigned values.
The block calculation is now performed.
The second and last element of
enum1
is generated and passed to the block, and block variables are assigned values and the block is computed.When an attempt to generate another element from
enum1
we obtainRuby handles the exception by breaking out of the block and returning
arr
. The elements ofarr
are then joined:and printed.
The second and last element of
enum0
is now generated, passed to the block, and the three block variables are assigned values.The remaining calculations are similar.
Some readers may be unfamiliar with the method Enumerable#each_with_object, which is widely used. Read the doc, but note that here it yields the same result as the code written as follows.
By using
each_with_object
we avoid the need for the statementarr = [a+b]
and the statementputs arr.join(' ')
. The functions of those two statements are of course there in the line usingeach_with_object
, but most Ruby users prefer the flow when when chainingeach_with_object
tojoin(' ')
. One other difference is that the value ofarr
is confined toeach_with_object
's block, which is good programming practice.