0

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"]
branquito
  • 3,864
  • 5
  • 35
  • 60
  • Possible duplicate of [Ruby: How to make IRB print structure for Arrays and Hashes](http://stackoverflow.com/questions/703049/ruby-how-to-make-irb-print-structure-for-arrays-and-hashes) – Wand Maker Jun 09 '16 at 18:28
  • 1
    Thanks for the ✅, but in future consider waiting longer before making a selection. Other members may have been working on answers and you don't want to discourage other answers. The point is, there's no rush. Many here wait at least a couple of hours before awarding the greenie. – Cary Swoveland Jun 09 '16 at 19:18

3 Answers3

3

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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

Try

('a'..'c').to_a.combination(2).each do |arr|
   puts arr.inspect
end
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

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.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191