Ruby字符串后结果异常是什么原因?
- 内容介绍
- 文章标签
- 相关推荐
本文共计223个文字,预计阅读时间需要1分钟。
使用当代代码:`\\t\\ttest\\t\\t.split(/\t/)` 预期以下结果:`=[, , test, , , ]` 但结果是:`=[, , test]` 为什么?
因为如果省略了 `limit` 参数,`split` 方法会返回剩余的所有空字符串。所以,如果字符串中包含多个连续的分割符,这些空字符串将被包含在结果数组中。
使用此代码:"\t\ttest\t\t\t".split(/\t/)
我期待以下结果:
=> ["", "", "test", "", "", ""]
但结果是:
=> ["", "", "test"]
为什么?
# Supply -1 as the limit parameter "\t\ttest\t\t\t".split(/\t/, -1) => ["", "", "test", "", "", ""]
这在String.split() documentation.中有详细说明
本文共计223个文字,预计阅读时间需要1分钟。
使用当代代码:`\\t\\ttest\\t\\t.split(/\t/)` 预期以下结果:`=[, , test, , , ]` 但结果是:`=[, , test]` 为什么?
因为如果省略了 `limit` 参数,`split` 方法会返回剩余的所有空字符串。所以,如果字符串中包含多个连续的分割符,这些空字符串将被包含在结果数组中。
使用此代码:"\t\ttest\t\t\t".split(/\t/)
我期待以下结果:
=> ["", "", "test", "", "", ""]
但结果是:
=> ["", "", "test"]
为什么?
# Supply -1 as the limit parameter "\t\ttest\t\t\t".split(/\t/, -1) => ["", "", "test", "", "", ""]
这在String.split() documentation.中有详细说明

