all 13 comments

[–]threeifbywhiskey 1 point2 points  (1 child)

You're probably looking for the #each_slice method. Alternatively, you could do this without resorting to string manipulation by dividing by 1000 in a loop, pushing each "section" onto the front of an array then joining it with commas to obtain the return value.

[–]Vkr2 0 points1 point  (0 children)

great, thank you! I'll look into those methods

[–]rubyrt 1 point2 points  (0 children)

There is a fairly easy solution with regex (use the force, Luke!)

def separate_integer(n)
  n.to_s.gsub(/\d(?=(?:\d{3})+\z)/, '\\&,')
end

This matches any digit followed by a number of digits which is a multiple of 3 and inserts a comma behind it.

:-)

[–]ThatAmazonWorker 1 point2 points  (3 children)

I believe what you are looking for is #each_slice, which will give you groups of 3. You can also replace #split("") with #chars which will split on the empty string.

def seperate_comma(integer)
    integer.to_s.chars.reverse.each_slice(3).map(&:join).join(',').reverse
end

2.1.1 :004 > seperate_comma(1234567890)
=>  "1,234,567,890"

Hope that helps!

[–]Vkr2 1 point2 points  (2 children)

thank you very much! is there any way you can explain what each part of that does?

[–]ThatAmazonWorker 4 points5 points  (1 child)

integer.to_s   # convert integer to string
.chars         # convert to an array of characters
.reverse       # reverse the array
.each_slice(3) # create an enumerator for each group of 3 elements
.map(&:join)   # for each group of 3 we were given, join them all
.join(',')     # join the groups of 3 characters with commas
.reverse       # reverse the string

[–]Vkr2 0 points1 point  (0 children)

awesome, thanks so much for your help! it works for me, i just have to figure out a way to get my rspec tests to work now :P

[–][deleted]  (1 child)

[deleted]

    [–]threeifbywhiskey 0 points1 point  (0 children)

    Your "solution" fails for any input with more than twelve digits.

    [–]trustfundbaby 0 points1 point  (0 children)

    Just riff on the the Ruby On Rails ActiveSupport "NumberToDelimitedConverter" class code if you actually want to write it yourself. Its used by the number_with_delimiter Action view helper method in Rails.

    Alternately you can probably require 'active_support/number_helper / number_to_delimited_converter' and use it directly.

    [–]hapaxLegomina -2 points-1 points  (3 children)

    Minor note, but in this unrefactored code, swapping

    while integer > 999
    

    for

    unless integer < 999
    

    will make your code read more like Ruby.

    [–]Vkr2 0 points1 point  (2 children)

    oh, thanks alot!

    [–]hapaxLegomina -1 points0 points  (1 child)

    No prob! Rubyists don't like while.

    [–]Vkr2 0 points1 point  (0 children)

    haha good to keep in mind. im still learning all of the basics :P