I have 4 string variables name, quest, favorite_color, speed
that might be empty. I want to concatenate them all together, putting spaces between those that aren't empty. Simplicity of the code, i.e how simple is to to look at and understand, is more important than speed.
So:
name = 'Tim' quest = 'destroy' favorite_color = 'red' speed = 'fast'
becomes
'Tim destroy red fast'
and
name = 'Steve' quest = '' favorite_color = '' speed = 'slow'
becomes:
'Steve slow'
Note there is only 1 space between 'Steve' and 'slow'.
How do I do that (preferably in 1 line)?
Concatenation looks like this: a = "Nice to meet you" b = ", " c = "do you like blueberries?" a + b + c # "Nice to meet you, do you like blueberries?" You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.
Idiom #153 Concatenate string with integer. Create the string t as the concatenation of the string s and the integer i. auto t = s + std::to_string (i);
String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.
When you want to concatenate array elements with a string, you can use the array. join() method or * operator for this purpose.
[name, quest, favorite_color, speed].reject(&:empty?).join(' ')
Try [name,quest,favorite_color,speed].join(' ').squeeze(' ')
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