Skip to content

Instantly share code, notes, and snippets.

@9jaswag
Created May 30, 2019 11:24
Show Gist options
  • Save 9jaswag/0d1c79141cf0080f2791cd705fafcd36 to your computer and use it in GitHub Desktop.
Save 9jaswag/0d1c79141cf0080f2791cd705fafcd36 to your computer and use it in GitHub Desktop.
Number to words challenge
def find_unit(num, hash)
unit = hash.select { |key, _value| key <= num }
unit.keys.last
end
def num_to_words(num)
numbers_to_name = {
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'thousand'
}
return 'zero' if num.zero?
string = ''
while num > 0
unit = find_unit(num, numbers_to_name)
unit_name = numbers_to_name[unit]
if num == unit && num <= 100
string += " #{unit_name}"
return string
end
result = num / unit
string += if string.empty? && num >= 100
"#{numbers_to_name[result]} #{unit_name}"
else
" #{unit_name}"
end
modulo = num % unit
break if modulo.zero?
num = modulo
end
string
end
puts num_to_words(3)
puts num_to_words(103)
puts num_to_words(131)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment