1

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.

1
  • is the set of numbers in an array or is it a string? Commented Feb 13, 2015 at 0:31

2 Answers 2

2
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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.