Ruby 连接字符串并添加空格

标签 ruby string concatenation

我有 4 个字符串变量 name, quest, favorite_color, speed 可能是空的。我想将它们连接在一起,在不为空的那些之间放置空格。代码的简单性,即查看和理解的简单程度,比速度更重要。

所以:

name = 'Tim'
quest = 'destroy'
favorite_color = 'red'
speed = 'fast'

成为

'Tim destroy red fast'

name = 'Steve'
quest = ''
favorite_color = ''
speed = 'slow'

变成:

'Steve slow'

注意“Steve”和“slow”之间只有 1 个空格。

我该怎么做(最好在一行中)?

最佳答案

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

关于Ruby 连接字符串并添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2434885/

相关文章:

c++ - 如何以漂亮的格式放置不同的 C 字符串?

python - pandas 中的 str.zfill() 有 ' 字符问题

r - 将数字连接到字符串输出中,格式化每个数字以采用相同的字符宽度

ruby-on-rails - Rswag 和 Rspec : Undefined method for URL parameter

ruby-on-rails - 在 rake db :create 期间无法将 fixnum 转换为字符串

java - 如何将列表拆分为给定数量的子列表?

MySQL group_concat 从两个表返回值(包括 NULL)

python - 像在 MATLAB 中一样在 Python 中连接矩阵/向量?

ruby-on-rails - 帮助重构这个讨厌的 Ruby if/else 语句

ruby-on-rails - RoR,Tire和Elasticsearch