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.
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. Btw, you don't need to use variables to make this work.
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.
It is easier and more readable with interpolation instead of concatenation:
dear = ""
string = "hello#{ ' my dear' unless dear.empty? }, good morning!"
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
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