Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: how to insert a conditional into a string concatenation

Tags:

ruby

In a string concatenation, is it possible to include a conditional directly into the statement?

In the example below, I want "my dear" to be concatenated only if the dear list is not empty.

dear = ""

string = "hello" + " my dear" unless dear.empty? + ", good morning!" 

But the result is an error: undefined method '+' for true

I know the alternative would be to define an additional variable before this statement but I would like to avoid this.

like image 673
sqrcompass Avatar asked Feb 21 '15 17:02

sqrcompass


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 you concatenate two variables 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 a character to a string in Ruby?

You can use the + operator to append a string to another. In this case, a + b + c , creates a new string. Btw, you don't need to use variables to make this work.

What's the difference between concatenation and interpolation Ruby?

Concatenation allows you to combine to strings together and it only works on two strings. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable.


2 Answers

It is easier and more readable with interpolation instead of concatenation:

dear = ""

string = "hello#{ ' my dear' unless dear.empty? }, good morning!"
like image 124
Rustam A. Gasanov Avatar answered Oct 17 '22 07:10

Rustam A. Gasanov


In this case, you would be better off using ternary operators.

string = "hello" + (dear.empty? ? "" : " my dear") + ", good morning!" 

The syntax goes like

condition ? if true : if false
like image 36
Amit Joki Avatar answered Oct 17 '22 08:10

Amit Joki