HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Number to words problem

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
problemwordsnumber

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 > 0
    result  0
    result  0
    result  0 
    if writing == 1 && left_over > 0
      result  0
    result  "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"

Solution

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.)

Code Snippets

writing, integer = integer.divmod(1_000_000)

Context

StackExchange Code Review Q#40776, answer score: 3

Revisions (0)

No revisions yet.