Skip to content

Instantly share code, notes, and snippets.

@cnocon
Last active December 23, 2015 14:59
Show Gist options
  • Select an option

  • Save cnocon/6652977 to your computer and use it in GitHub Desktop.

Select an option

Save cnocon/6652977 to your computer and use it in GitHub Desktop.
The english number problem from Learn to Program by Chris Pine.
# This program should take a number, like 22, and return the English version of it
#(in this case, the string 'twenty-two').
#For now, let’s have it work only on integers from 0 to 99999:
puts "Provide a number greater than or equal to 0 but less than 100,000"
num = gets.chomp.to_i
def englishnum number
if number < 0 || number > 99999
puts "Please enter a number greater than or equal to 0 but less than 100,000"
end
if number == 0
puts "Zero"
end
number_string = ''
ones_places = %w[one two three four five six seven eight nine]
teens_places = %w[eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen]
tens_places = %w[ten twenty thirty fourty fifty sixty seventy eighty ninety]
#THOUSANDS (we'll find how many thousands are here)
left = number
write = left/1000
left = left - write*1000
if write > 0 #if there are thousands
thousands = englishnum write #recursion is here
if write >= 1 && write <= 9
number_string = number_string + ones_places[write - 1] + " thousand"
end
if write >= 11 && write <= 19
number_string = number_string + teens_places[write - 11] + " thousand"
end
if (write >= 20 && write <= 99) || write == 10
digits = write.to_s.split('')
first = digits[0].to_i
second = digits[1].to_i
if first == 0 && second > 0
number_string = number_string + ones_places[second-1] + " thousand"
end
if first >= 1 && first <= 9 && second == 0
number_string = number_string + tens_places[first-1] + " thousand"
end
if first >= 1 && first <= 9 && second > 0
number_string = number_string + tens_places[first - 1] + ones_places[second-1] + " thousand"
end
end
if left > 0
number_string = number_string + " " #so we don't write two thousandfive hundred; leaving a space for the remaining left number
end
end
#HUNDREDS
write = left/100
left = left - write*100
if write > 0 #if there are hundreds
number_string = number_string + ones_places[write-1] + " hundred"
end
if left > 0
number_string = number_string + " "
end
#TENS
write = left/10
left = left - write*10 #ones place
if write > 0
number_string = number_string + tens_places[write-1]
end
if left > 0
number_string = number_string + " " + ones_places[left-1]
end
return number_string
end
puts englishnum(num)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment