ruby - 无法将 nil 转换为字符串——已编辑以重述所有失败的尝试

标签 ruby null

在我的代码中,我希望 current_part 有时为 nil,并且我想运行一些代码(在 if 中 block )当情况并非如此。

使用 script/server --debugger,我确定 current_part 在发生以下错误时实际上是 nil .

所有以下版本都会在第二行生成 can't convert nil into String 错误:

#

  def map_concepts_to_part(part, current_part)
     if current_part
        part.concepts.map { |concept| content_tag(:li, "stuff...")}.join
      end
  end

#

  def map_concepts_to_part(part, current_part)
     if test_if_exists(current_part)
        part.concepts.map { |concept| content_tag(:li, "stuff...")}.join
      end
  end

  def test_if_exists(test_subject)
    test_subject rescue nil
  end

#

  def map_concepts_to_part(part, current_part)
     if test_if_complete(current_part)
        part.concepts.map { |concept| content_tag(:li, "stuff...")}.join
      end
  end

  def test_if_complete(test_subject)
    test_subject.id rescue nil
  end

#

  def test_if_complete(part, current_part)
     unless current_part.to_s == ""
        part.concepts.map { |concept| content_tag(:li, "stuff...")}.join
      end
  end

#

  def test_if_complete(part, current_part)
     unless current_part.nil?
        part.concepts.map { |concept| content_tag(:li, "stuff...")}.join
      end
  end

#

PS,上面每一行被截断的行是:

part.concepts.map { |concept| content_tag(:li, "Concept: “" + concept.title + "”", :class => "one_concept") + content_tag(:li, "Attached images (" + concept.images.size.to_s + ")", :class => "all_images") + content_tag(:li, "Attached docs (XX)", :class => "all_docs")}.join

最佳答案

current_partnil 时,测试 current_part.to_s == "" 在我的 ruby​​ 系统上返回 true .与其他一些语言不同,您可以说 nil.to_snil.nil? 并让它们工作。我认为还有其他原因导致了问题。你能展示更多代码吗?

(我的测试是在 ruby​​ 1.8.6 中进行的)

编辑:环顾四周,通常导致上述错误的是 "text"+ nil 等表达式,而不是 nil.to_s。你身边有这样的东西吗?

关于ruby - 无法将 nil 转换为字符串——已编辑以重述所有失败的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460316/

相关文章:

ruby - 许多嵌套 `for` 循环取决于变量

ruby-on-rails - 给定列号和行号,使用 Axlsx gem 修改特定单元格值

html - 如何在 View /索引上构建带导轨的勾选框

java - 如何改进 Guava Optional 的 mockito 默认行为?

Java DocumentBuilderFactory.parse();返回空文档

ruby - 为什么 URI.escape 不转义单引号?

ruby-on-rails - 邮件在 ruby​​ on rails 中合并,但数量很多

c - 如何删除 C 中的 NULL 输入?

mysql - 查询选择所有字段不为空

java - 检查字段是否为空