Ruby concatenate strings and add spaces

折月煮酒 提交于 2019-12-04 07:57:06

问题


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


回答1:


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



回答2:


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




回答3:


You can use inject:

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


来源:https://stackoverflow.com/questions/2434885/ruby-concatenate-strings-and-add-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!