Sixty4Bit Sixty4Bit - 9 months ago 59
Ruby Question

Ruby String concatenation and ternary don't play nice?

On the following code, the third line errors with:
TypeError: can't convert false into String

line = "some default text"
line << " some more text" unless more.empty?
line << (even_more.empty?) ? " done." : " and even more text"

What is a better way to do this?


Those parens are necessary because << has higher precedence than ? (precedence table). Solution:

line << (even_more.empty? ? " done." : " and even more text")

As a side note, notice that you can take a functional approach when building arrays:

line = [
  "some default text",
  ("some more text" unless more.empty?),
  even_more.empty? ? "done." : "and even more text",
].compact.join(" ")