通过Odin项目工作并坚持进行Ruby练习,在那里你输入一个数字输入并吐出数字的飞机英文版本。获取错误参考下面的粗体部分(第32行)
def englishNumber number
if number < 0 # No negative numbers.
return 'Please enter a number that isn\'t negative.'
end
if number == 0
return 'zero'
end
numString = '' # This is the string we will return.
onesPlace = ['one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine']
tensPlace = ['ten', 'twenty', 'thirty', 'forty', 'fifty',
'sixty', 'seventy', 'eighty', 'ninety']
teenagers = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen']
left = number
write = left/10000
left = left - write*10000
if write > 0
if ((write == 1) and (left > 0))
**numString = numString + teenagers[left-1] + ' thousand'**
left = 0
else
numString = numString + tensPlace[write-1] + ' thousand'
if left > 0
numString = numString + '-'
end
end
write = left/1000
left = left - write*1000
if write > 0
if left > 0
numString = numString + ' '
end
end
write = left/100
left = left - write*100
if write > 0
if left > 0
numString = numString + ' '
end
end
write = left/10
left = left - write*10
if write > 0
if ((write == 1) and (left > 0))
left = 0
else
numString = numString + tensPlace[write-1]
# The "-1" is because tensPlace[3] is 'forty', not 'thirty'.
end
if left > 0
numString = numString + '-'
end
end
write = left
left = 0
if write > 0
numString = numString + onesPlace[write-1]
# The "-1" is because onesPlace[3] is 'four', not 'three'.
end
# Now we just return "numString"...
numString
end
puts englishNumber 10100
答案 0 :(得分:0)
问题出在语句teenagers[left-1]
上。对于输入10100,
left
= 100且teenagers[100-1]
= teenagers[99]
= nil
。
您无法将字符串与nil
对象连接起来。你可以通过多种方式解决这个问题。
一种方法是用
替换你的病情if ((write == 1) and (left > 0) and teenagers[left-1])
如果值不是nil
如果您运行该程序,则应该能够看到ten thousand-
输入10100
。现在,处理您的算法,使其返回输入中hundreds
的数量。
在end
内的if .. else
阻止后,您还错过了if write > 0
希望这有帮助!