ruby - Refactor method to add commas to a string of numbers -
this question has reply here:
how format number 1000 “1 000” 11 answersi working on method add together commas number passed. i.e. separate_commas(1000) homecoming "1,000" or separate_commas(100000) homecoming "100,000"...etc.
now i've solved it, i'm wondering how refactor without regular expressions. appreciate suggestions, give thanks 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 homecoming x end
not pretty, little more ruby-esque
num.to_s.reverse .split('').each_slice(3).to_a .map{|num| num.reverse.join('')}.reverse.join(',')
ruby refactoring
No comments:
Post a Comment