branquito branquito - 6 months ago 9
Ruby Question

Printing array of arrays, each internal on separate line

Showing my interactive irb session:

2.3.0 :005 > ('a'..'c').to_a.combination(2).to_a
=> [["a", "b"], ["a", "c"], ["b", "c"]]

2.3.0 :006 > ('a'..'c').to_a.combination(2).to_a.each do |arr|
2.3.0 :007 > puts arr
2.3.0 :008?> end
a
b
a
c
b
c
=> [["a", "b"], ["a", "c"], ["b", "c"]]


How can I get this array of arrays to show each internal array on separate line, like so..?

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

Answer

Use Kernel#p rather than Kernel#puts.

('a'..'c').to_a.combination(2).each { |a| p a }
["a", "b"]
["a", "c"]
["b", "c"]

Note that, while Array#combination without a block returns an enumerator, you don't have to convert it to an array before each'ing it.