Reputation: 4034
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
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
Reputation: 30056
Try
('a'..'c').to_a.combination(2).each do |arr|
puts arr.inspect
end
Upvotes: 1
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