-4

With the below my whole dynamic array outputs, 10 per line - I would like to setup a param to have 3 array items per line, after 3 another line is created.

...     
     while i < arr.length
          print "Define types of coffee drinks: "
          coffee = gets.chomp
          arr[i] = coffee
          i += 1
        end
        puts arr.join(", ")
      break
...

For instance after my dynamic array is created it outputs like:

black iced coffee, cold brew, espresso, flat white, frap, latte, drip, fancy, smancy

All 10 on one line, I'd like it to output like:

black iced coffee, cold brew, espresso,
flat white, frap, latte, 
drip, fancy, smancy
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • Your question is unclear, because you have not provided a [mcve]. What is `arr`? Your code sample should be **complete** - i.e. I should be able to copy+paste and run it myself. – Tom Lord Jan 29 '18 at 22:56
  • The second line in your output (with four elements) is a typo, right? And you should `a.push(coffee)` rather than worry about `i`. – mu is too short Jan 29 '18 at 23:25

3 Answers3

2
array.each_slice(3).with_index do |part, ind|
  puts part.join(", ") + (ind == 3 ? "" : ",")
end

is probably what you want to do.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Josh Brody
  • 5,153
  • 1
  • 14
  • 25
2

Here's a simple solution that almost gets what you asked for:

array.each_slice(3) { |part| puts part.join(', ') }

#=> black iced coffee, cold brew, espresso
    flat white, frap, latte, drip
    fancy, smancy

However, this is missing the final comma on the first two lines.

If this is important, you might try to add it like so:

array.each_slice(3) { |part| puts part.join(', ') + ',' }

#=> black iced coffee, cold brew, espresso,
    flat white, frap, latte, drip,
    fancy, smancy,

...but now it's also on the last line!

There's probably a slightly more elegant way to do this, but it's a bit fiddly... How about:

array.each_slice(3).with_index do |part, i|
  puts part.join(", ") + (array.size % 3 == i ? '' : ',')
end

#=> black iced coffee, cold brew, espresso,
    flat white, frap, latte, drip,
    fancy, smancy
Tom Lord
  • 27,404
  • 4
  • 50
  • 77
2

I'd probably use each_slice and join to build the individual lines:

a.each_slice(3).map { |a| a.join(', ') }

and then join again to join the lines together:

puts a.each_slice(3).map { |a| a.join(', ') }.join(",\n")

This assumes, of course, that each line except the last is supposed to contain three elements and that the second line of your sample output is a typo.

mu is too short
  • 426,620
  • 70
  • 833
  • 800