0

I was working on a method to add commas to a number that is passed. I.E. separate_commas(1000) would return "1,000" or separate_commas(100000) would return "100,000"...etc.

Now that I've solved it, I'm wondering how I could refactor without regular expressions. Would appreciate suggestions, thank you in advance. Ruby 2.1.1p76

def separate_comma(x)
  x=x.to_s
  len=-4
  until len.abs > x.length
    x.insert(len, ',')
    len-=4
  end
  return x
end
hummmingbear
  • 2,294
  • 5
  • 25
  • 42
  • 1
    You might look at how Rails implements its `number_with_delimiter` method: https://github.com/rails/rails/blob/8607577fc8f2d5767d9fc8001b3985fa541aa557/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb – Dylan Markow Oct 31 '14 at 17:56
  • I haven't worked with Rails, just using Ruby right now. – hummmingbear Oct 31 '14 at 17:59
  • What is your goal of refactoring this? E.g. have you thought about how you support internationalization in your app, and what should this function do (should it adapt to locale) – Brandin Oct 31 '14 at 18:05
  • @CarySwoveland Actually, the question is not an exact duplicate. The linked question has a different delimiter (but the essence is the same). Beware of that. Your answer is good for this question but not for the linked one. But it's not only you. – sawa Oct 31 '14 at 20:05
  • Thanks. I fixed it with `def separate(n,c=' ')...`. – Cary Swoveland Oct 31 '14 at 20:19
  • @CarySwoveland Yes, I am not supposed to solve this one with Regular Expressions which the one you linked to is doing. – hummmingbear Nov 01 '14 at 20:10
  • You have a point, but note that three of the answers to the previous question did not use a regular expression. – Cary Swoveland Nov 01 '14 at 20:19

1 Answers1

0

Not exactly pretty, but it is a little more ruby-esque

num.to_s.reverse
        .split('').each_slice(3).to_a
        .map{|num| num.reverse.join('')}.reverse.join(',')
Brennan
  • 5,632
  • 2
  • 17
  • 24
  • That's pretty close to @Yardboy's earlier answer, though some of the operations are in a different order (e.g., `num.reverse.to_s`). You don't need `to_a`, btw. – Cary Swoveland Oct 31 '14 at 20:29