在我的代码中,我希望 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_part
为 nil
时,测试 current_part.to_s == ""
在我的 ruby 系统上返回 true
.与其他一些语言不同,您可以说 nil.to_s
和 nil.nil?
并让它们工作。我认为还有其他原因导致了问题。你能展示更多代码吗?
(我的测试是在 ruby 1.8.6 中进行的)
编辑:环顾四周,通常导致上述错误的是 "text"+ nil
等表达式,而不是 nil.to_s
。你身边有这样的东西吗?
关于ruby - 无法将 nil 转换为字符串——已编辑以重述所有失败的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460316/