继续您的示例代码:
>> input = "dog cat"
=> "dog cat"
>> output = input.strip.split /\s+/
=> ["dog", "cat"]
>> joined = output.join ' '
=> "dog cat"
还要记住,Ruby 有几个帮助程序,例如%w
和 ,%W
用于将字符串转换为单词数组。如果您从一组单词开始,每个单词在其单个项目之前和之后都可能有空格,您可以尝试这样的操作:
>> # `input` is an array of words that was populated Somewhere Else
>> # `input` has the initial value [" dog ", "cat\n", "\r tribble\t"]
>> output = input.join.split /\s+/
=> ["dog", "cat", "tribble"]
>> joined = output.join ' '
=> "dog cat tribble"
不带任何参数的调用String#join
会将字符串数组项连接在一起,它们之间没有分隔,这似乎是在您的示例中所做的,您只需将数组呈现为字符串
>> @notice = output
>> # @notice will render as 'dogcat'
相对于:
>> @notice = input.join.split(/\s+/).join ' '
>> # @notice will render as 'dog cat'
你去吧。