Colton Seal
Colton Seal

Reputation: 379

Looping through array ruby

I have a set of numbers 123456789

I am writing a loop, so for every 3 numbers/characters it insert a comma, and then starts a new line.

What type of loop would I use for this? And how do I tell ruby for every 3 numbers? "123456.each_char.limit(3)"? I I know limit isnt correct but hopefully im getting the idea accross.

Upvotes: 1

Views: 106

Answers (2)

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

puts 123456789.to_s.gsub(/(.{3})/,"\\1,\n")

result :

123,
456,
789,

alternative loop way :

"123456789".each_char.with_index(1) do |item, index|
    if index % 3 == 0
        print item + ",\n"
    else
        print item
    end          
end

Upvotes: 2

Anthony
Anthony

Reputation: 15957

If the set of numbers is a string you can use Enumerable#each_slice to split up the characters into groups of 3 and then join them together before printing to the console:

[21] pry(main)> "123456789".chars.each_slice(3) { |a| p "#{a.join}," }
"123,"
"456,"
"789,"

Upvotes: 1

Related Questions