Sixty4Bit Sixty4Bit - 1 year ago 88
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?

Answer Source

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(" ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download