如何解决" `+':没有将nil隐式转换为String(TypeError)" Ruby中的错误

时间:2016-08-22 01:36:33

标签: ruby

通过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

1 个答案:

答案 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

,则最后一个表达式将为true

如果您运行该程序,则应该能够看到ten thousand-输入10100。现在,处理您的算法,使其返回输入中hundreds的数量。

end内的if .. else阻止后,您还错过了if write > 0

希望这有帮助!