Ruby concatenate strings and add spaces

后端 未结 3 437
不思量自难忘°
不思量自难忘° 2021-02-01 02:03

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\'

相关标签:
3条回答
  • 2021-02-01 02:07

    You can use inject:

    [name,quest,favorite_color,speed].inject("") {|k,v| v.empty? ? k : k << " " << v }.strip
    
    0 讨论(0)
  • 2021-02-01 02:08

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

    0 讨论(0)
  • 2021-02-01 02:30
    [name, quest, favorite_color, speed].reject(&:empty?).join(' ')
    
    0 讨论(0)
提交回复
热议问题