Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 339
Sixty4Bit Avatar asked Apr 12 '11 21:04

Sixty4Bit


People also ask

How do you concatenate a string with a variable in Ruby?

concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted to a character before concatenation. Parameters: This method can take the string object and normal string as the parameters.

How do I concatenate a string and a number in Ruby?

Concatenating strings or string concatenation means joining two or more strings together. In Ruby, we can use the plus + operator to do this, or we can use the double less than operator << .

How do you add two strings in Ruby?

You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.

What is ternary operator in Ruby?

What is a ternary operator in Ruby? A ternary operator is made of three parts, that's where the word “ternary” comes from. These parts include a conditional statement & two possible outcomes. In other words, a ternary gives you a way to write a compact if/else expression in just one line of code.


1 Answers

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(" ")
like image 185
tokland Avatar answered Sep 22 '22 07:09

tokland