开发者

Ruby concatenate strings and add spaces

开发者 https://www.devze.com 2022-12-22 23:13 出处:网络
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 ho

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 o开发者_JAVA技巧nly 1 space between 'Steve' and 'slow'.

How do I do that (preferably in 1 line)?


[name, quest, favorite_color, speed].reject(&:empty?).join(' ')


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


You can use inject:

[name,quest,favorite_color,speed].inject("") {|k,v| v.empty? ? k : k << " " << v }.strip
0

精彩评论

暂无评论...
验证码 换一张
取 消