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

ste*_*ble 2 ruby null

在我的代码中的一点,我希望current_part有时候nil,我想运行一些代码(在一个if块内),但事实并非如此.

使用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
Run Code Online (Sandbox Code Playgroud)

#

  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
Run Code Online (Sandbox Code Playgroud)

#

  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
Run Code Online (Sandbox Code Playgroud)

#

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

#

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

#

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
Run Code Online (Sandbox Code Playgroud)

Kat*_*one 5

测试current_part.to_s == ""返回true我的红宝石在系统中的current_partnil.不像一些其他语言,可以说nil.to_snil.nil?,让他们的工作.我认为还有其他因素导致问题.你能展示更多的代码吗?

(我的测试是在红宝石1.8.6)

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