Separate numbers with commas How should I approach refactoring this code?

def separate_comma(number)
  a = number.to_s.split('')
  b = a.size/3.0
  if a.size &lt; 4
    p number.to_s 
  elsif a.size%3 == 0
    n = -4
    (b.to_i-1).times do |i|
      a.insert(n, ',')
      n -= 4
    end
    p a.join("")
  else
      n = -4
    b.to_i.times do |i|
      a.insert(n, ',')
      n -= 4
    end
  p a.join("")
  end
end


separate_comma(97425)    # =&gt; "97,425"
separate_comma(89552600) # =&gt; "895,926,600"
separate_comma(0)       # =&gt; "0"
separate_comma(100)     # =&gt; "100"
I am not sure how hard may be for a newbie to take on functional programming, but if you are interested in new ways of programming, check it out. A more specific article on Ruby: FP with Ruby. If you think in terms of expressions (what things are) instead of statements (update, insert, delete, ...), code is more declarative (and usually shorter). I'll use no regexps to show an alternative approach to the existing answer:
def separate_comma(number)
  reverse_digits = number.to_s.chars.reverse
  reverse_digits.each_slice(3).map(&amp;:join).join(&quot;,&quot;).reverse
end

If you want to support decimals:
def separate_comma(number)
  whole, decimal = number.to_s.split(&quot;.&quot;)
  whole_with_commas = whole.chars.to_a.reverse.each_slice(3).map(&amp;:join).join(&quot;,&quot;).reverse
  [whole_with_commas, decimal].compact.join(&quot;.&quot;)
end