This is a very long solution I've been working on to a Number to Words problem. I've identified that there's a lot of repeating logic (e.g. 'if writing > 0', 'writing = integer /',).
- How would you refactor this?
- When refactoring is there a process you use?
- For readability sake would it be better to break this method into various pieces? Why?
def in_words (integer) ones_array = ['zero','one','two','three','four','five','six','seven','eight','nine'] teens_array = ['blank','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'] tens_array = ['blank','ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'] result = "" #FOR MILLIONS writing = integer / 1_000_000 left_over = integer % 1_000_000 if writing > 0 result << in_words(writing) << "million " integer = left_over end #FOR THOUSANDS writing = integer / 1000 left_over = integer % 1000 if writing > 0 result << in_words(writing) << "thousand " integer = left_over end #FOR HUNDREDS writing = integer / 100 left_over = integer % 100 if writing > 0 result << in_words(writing) << "hundred " integer = left_over end #FOR TENS!!! writing = integer / 10 left_over = integer % 10 if writing > 0 if writing == 1 && left_over > 0 result << teens_array[left_over] left_over = 0 else result << tens_array[writing] end end writing = left_over #FOR ONES!!!! if writing > 0 result << ones_array[writing] end result end p in_words(4) # => "four" p in_words(15) # => "fifteen" p in_words(92) # => "ninety two" or "ninety-two" p in_words(101) # => "one hundred one" p in_words(9915) # => "nine thousand nine hundred fifteen" p in_words(1456789) # => #"one million four hundred fifty six thousand seven hundred eighty nine"