Ruby 被空格分割 [英] Ruby split by whitespace

查看:59
本文介绍了Ruby 被空格分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个 Ruby 函数,将输入拆分为任何类型的空格,并从结果中删除所有空格?例如,如果输入是

 aa bbbcc dd ee

然后返回一个数组["aa", "bbb", "cc", "dd", "ee"].

解决方案

以下应该适用于您提供的示例:

str.gsub(/\s+/m, ' ').strip.split(" ")

它返回:

["aa", "bbb", "cc", "dd", "ee"]

代码含义:

/\s+/m 是更复杂的部分.\s 表示空格,所以 \s+ 表示一个或多个空格字母.在/m部分,m被称为修饰符,在这种情况下,它的意思是,multiline,意思是访问多行,而不只是其中的一行是默认行为.所以,/\s+/m 意味着,找到一个或多个空格的序列.

gsub 表示全部替换.

strip 相当于其他语言中的 trim ,去除字符串前后的空格.

因为,我正在写解释,可能会出现这样的情况:在字符串的末尾或开头以和结束行字符结尾.

为了安全

代码可以写成:

str.gsub(/\s+/m, ' ').gsub(/^\s+|\s+$/m, '').split(" ")

如果你有:

str = "\n aa bbb\n cc dd ee\n\n"

然后你会得到:

["aa", "bbb", "cc", "dd", "ee"]

新代码的含义:

^\s+ 字符串开头的空格序列

\s+$ 字符串末尾的空格序列

所以 gsub(/^\s+|\s+$/m, '') 表示删除字符串开头和字符串末尾的任何空格序列.>

How can I write a Ruby function that splits the input by any kind of whitespace, and remove all the whitespace from the result? For example, if the input is

 aa bbb
cc    dd ee

Then return an array ["aa", "bbb", "cc", "dd", "ee"].

解决方案

The following should work for the example you gave:

str.gsub(/\s+/m, ' ').strip.split(" ")

it returns:

["aa", "bbb", "cc", "dd", "ee"]

Meaning of code:

/\s+/m is the more complicated part. \s means white space, so \s+ means one ore more white space letters. In the /m part, m is called a modifier, in this case it means, multiline, meaning visit many lines, not just one which is the default behavior. So, /\s+/m means, find sequences of one or more white spaces.

gsub means replace all.

strip is the equivalent of trim in other languages, and removes spaces from the front and end of the string.

As, I was writing the explanation, it could be the case where you do end up with and end-line character at the end or the beginning of the string.

To be safe

The code could be written as:

str.gsub(/\s+/m, ' ').gsub(/^\s+|\s+$/m, '').split(" ")

So if you had:

str = "\n     aa bbb\n    cc    dd ee\n\n"

Then you'd get:

["aa", "bbb", "cc", "dd", "ee"]

Meaning of new code:

^\s+ a sequence of white spaces at the beginning of the string

\s+$ a sequence of white spaces at the end of the string

So gsub(/^\s+|\s+$/m, '') means remove any sequence of white space at the beginning of the string and at the end of the string.

这篇关于Ruby 被空格分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆