Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby concatenate strings and add spaces

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)?

like image 391
David Oneill Avatar asked Mar 12 '10 18:03

David Oneill


People also ask

How do you concatenate strings in Ruby?

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.

How do you concatenate a string and an integer in Ruby?

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);

What is string interpolation in Ruby?

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.

How do you join a string array in Ruby?

When you want to concatenate array elements with a string, you can use the array. join() method or * operator for this purpose.


2 Answers

[name, quest, favorite_color, speed].reject(&:empty?).join(' ') 
like image 167
Aaron Hinni Avatar answered Sep 18 '22 15:09

Aaron Hinni


Try [name,quest,favorite_color,speed].join(' ').squeeze(' ')

like image 24
bta Avatar answered Sep 21 '22 15:09

bta