在以下代码中,第三行错误: TypeError:无法将false转换为String
line = "some default text"
line << " some more text" unless more.empty?
line << (even_more.empty?) ? " done." : " and even more text"
有什么更好的方法可以做到这一点?
答案 0 :(得分:20)
这些parens是必要的,因为<<
的优先级高于?
(precedence table)。解决方案:
line << (even_more.empty? ? " done." : " and even more text")
作为旁注,请注意您在构建数组时可以采用功能方法:
line = [
"some default text",
("some more text" unless more.empty?),
even_more.empty? ? "done." : "and even more text",
].compact.join(" ")