【问题标题】:Ruby code doesn't work [closed]Ruby代码不起作用[关闭]
【发布时间】:2015-12-24 04:02:20
【问题描述】:

/Users/danielwheeler/Desktop/Scr​​een Shot 2015-09-26 at 13.18.16.png

我正在尝试制作一种将数字作为输入并将其转换为字符串的方法。不知道出了什么问题。

来自 sublime 的错误信息是:

/Users/danielwheeler/Desktop/code/projects/learn_to_program/ch10-nothing-new/english_number.rb:30:in `block in english_number': no implicit conversion of nil into String (TypeError)
    from /Users/danielwheeler/Desktop/code/projects/learn_to_program/ch10-nothing-new/english_number.rb:23:in `each'
    from /Users/danielwheeler/Desktop/code/projects/learn_to_program/ch10-nothing-new/english_number.rb:23:in `each_with_index'
    from /Users/danielwheeler/Desktop/code/projects/learn_to_program/ch10-nothing-new/english_number.rb:23:in `english_number'
    from /Users/danielwheeler/Desktop/code/projects/learn_to_program/ch10-nothing-new/english_number.rb:44:in `<main>'
[Finished in 0.1s with exit code 1]

【问题讨论】:

  • 你的问题是什么?
  • 欢迎来到 Stack Overflow。不要提供指向您的代码的链接。特别是,不要在评论中提供指向您的代码的链接。相反,将您的代码减少到演示您所询问的问题所需的最低限度。链接 rot 和 cmets 用于澄清,而不是代码。您还需要最少的样本输入来演示问题以及预期的输出。照原样,你的问题是题外话。

标签: ruby if-statement methods each


【解决方案1】:

我检查了你的代码,发现了一些问题:

 num_array.reverse.each_with_index { |value , index|
    if index % 3 == 0 && num_array[index] != 0 
      num_string = num_string << ones_place[value-1]
    elsif index % 3 == 0 && value > 0 && num_array[index] != 0
      num_string = num_string << other_place[index/3] << ones_place[value-1]
    elsif index % 3 == 1
      num_string = num_string << tens_place[value-1]
    elsif index & 3 == 2
      num_string = num_string << other_place[0] << ones_place[value-1]
    end
  }

ones_place[value-1] 可能为 nil,您尝试将 nil 添加到字符串中,因此引发了 TypeError。如果ones_place[value-1] 为nil,则应将其更改为字符串,只需使用to_s 方法或使用+ 将字符串相加即可。

"" << nil
TypeError: no implicit conversion of nil into String

"" << nil.to_s
=> ""

我修改代码如下,脚本可以运行,没有发现错误,但不知道结果对不对,你自己检查一下吧。

  num_array.reverse.each_with_index { |value , index|
    puts "#{value} and #{index}"
    if index % 3 == 0 && num_array[index] != 0
      num_string = num_string + ones_place[index-1]
    elsif index % 3 == 0 && value > 0 && num_array[index] != 0
      num_string = num_string + other_place[index/3] + ones_place[index-1]
    elsif index % 3 == 1
      num_string = num_string + tens_place[index-1]
    elsif index & 3 == 2
      num_string = num_string + other_place[0] + ones_place[index-1]
    end
  }

我建议你在脚本中添加一些调试代码,它可以帮助你尽快发现问题。

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 2018-04-01
    • 2015-03-04
    • 2014-02-28
    • 2013-10-11
    • 1970-01-01
    • 2014-01-05
    • 2014-12-05
    相关资源
    最近更新 更多