Number to words problem 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 &gt; 0
    result &lt;&lt; in_words(writing) &lt;&lt; "million "
    integer = left_over
  end

  #FOR THOUSANDS
  writing = integer / 1000
  left_over = integer % 1000

  if writing &gt; 0
    result &lt;&lt; in_words(writing) &lt;&lt; "thousand "
    integer = left_over
  end

  #FOR HUNDREDS 
  writing = integer / 100
  left_over = integer % 100

  if writing &gt; 0
    result &lt;&lt; in_words(writing) &lt;&lt; "hundred "
    integer = left_over
  end

  #FOR TENS!!!
  writing = integer / 10
  left_over = integer % 10

  if writing &gt; 0 
    if writing == 1 &amp;&amp; left_over &gt; 0
      result &lt;&lt; teens_array[left_over]
      left_over = 0
    else
      result &lt;&lt; tens_array[writing]
    end
  end

  writing = left_over

  #FOR ONES!!!!
  if writing &gt; 0
    result &lt;&lt; ones_array[writing]
  end

  result

end


p in_words(4) # =&gt; "four"
p in_words(15) # =&gt; "fifteen"
p in_words(92) # =&gt; "ninety two" or "ninety-two"
p in_words(101) # =&gt; "one hundred one" 
p in_words(9915) # =&gt; "nine thousand nine hundred fifteen"
p in_words(1456789) # =&gt; 
    #"one million four hundred fifty six thousand seven hundred eighty nine"
You should use Ruby's Numeric#divmod function:

writing, integer = integer.divmod(1_000_000)


Your function parameter claims to accept an integer, so you should also handle negative inputs.  (It shouldn't be hard to prepend "negative " and flip the sign.)