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?
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.
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 << .
You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.
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.
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(" ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With