branquito
branquito

Reputation: 4034

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

Upvotes: 0

Views: 101

Answers (3)

Wayne Conrad
Wayne Conrad

Reputation: 107969

Use Kernel#pp from the Ruby PP (pretty print) library. pp is like Kernel#p:

require "pp"

pp ('a'..'e').to_a.combination(2).to_a
# => [["a", "b"], ["a", "c"], ["b", "c"]]

except that pp automatically splits long output onto multiple lines:

pp ('a'..'e').to_a.combination(2).to_a

[["a", "b"],
 ["a", "c"],
 ["a", "d"],
 ["a", "e"],
 ["b", "c"],
 ["b", "d"],
 ["b", "e"],
 ["c", "d"],
 ["c", "e"],
 ["d", "e"]]

Since Array#combination returns an Enumeration, we used #to_a to convert it to an array. Without the #to_a, pp just shows this:

pp ('a'..'e').to_a.combination(2)
# => #<Enumerator: ...>

which is probably not what is wanted.

Upvotes: 1

Ursus
Ursus

Reputation: 30056

Try

('a'..'c').to_a.combination(2).each do |arr|
   puts arr.inspect
end

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110665

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.

Upvotes: 3

Related Questions