patternrubyModerate
Separate numbers with commas
Viewed 0 times
withnumberscommasseparate
Problem
How should I approach refactoring this code?
def separate_comma(number)
a = number.to_s.split('')
b = a.size/3.0
if a.size "97,425"
separate_comma(89552600) # => "895,926,600"
separate_comma(0) # => "0"
separate_comma(100) # => "100"Solution
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:
If you want to support decimals:
def separate_comma(number)
reverse_digits = number.to_s.chars.reverse
reverse_digits.each_slice(3).map(&:join).join(",").reverse
endIf you want to support decimals:
def separate_comma(number)
whole, decimal = number.to_s.split(".")
whole_with_commas = whole.chars.to_a.reverse.each_slice(3).map(&:join).join(",").reverse
[whole_with_commas, decimal].compact.join(".")
endCode Snippets
def separate_comma(number)
reverse_digits = number.to_s.chars.reverse
reverse_digits.each_slice(3).map(&:join).join(",").reverse
enddef separate_comma(number)
whole, decimal = number.to_s.split(".")
whole_with_commas = whole.chars.to_a.reverse.each_slice(3).map(&:join).join(",").reverse
[whole_with_commas, decimal].compact.join(".")
endContext
StackExchange Code Review Q#28054, answer score: 14
Revisions (0)
No revisions yet.