Ruby字符串后结果异常是什么原因?

更新于
2026-10-09 21:03:39
0阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计223个文字,预计阅读时间需要1分钟。

Ruby字符串后结果异常是什么原因?

使用当代代码:`\\t\\ttest\\t\\t.split(/\t/)` 预期以下结果:`=[, , test, , , ]` 但结果是:`=[, , test]` 为什么?

因为如果省略了 `limit` 参数,`split` 方法会返回剩余的所有空字符串。所以,如果字符串中包含多个连续的分割符,这些空字符串将被包含在结果数组中。

使用此代码:

"\t\ttest\t\t\t".split(/\t/)

我期待以下结果:

=> ["", "", "test", "", "", ""]

但结果是:

=> ["", "", "test"]

为什么?

Ruby字符串后结果异常是什么原因?

如果省略limit参数,则返回的空字段将保留在返回的数组之外.如果是否定的,则返回:

# Supply -1 as the limit parameter "\t\ttest\t\t\t".split(/\t/, -1) => ["", "", "test", "", "", ""]

这在String.split() documentation.中有详细说明

本文共计223个文字,预计阅读时间需要1分钟。

Ruby字符串后结果异常是什么原因?

使用当代代码:`\\t\\ttest\\t\\t.split(/\t/)` 预期以下结果:`=[, , test, , , ]` 但结果是:`=[, , test]` 为什么?

因为如果省略了 `limit` 参数,`split` 方法会返回剩余的所有空字符串。所以,如果字符串中包含多个连续的分割符,这些空字符串将被包含在结果数组中。

使用此代码:

"\t\ttest\t\t\t".split(/\t/)

我期待以下结果:

=> ["", "", "test", "", "", ""]

但结果是:

=> ["", "", "test"]

为什么?

Ruby字符串后结果异常是什么原因?

如果省略limit参数,则返回的空字段将保留在返回的数组之外.如果是否定的,则返回:

# Supply -1 as the limit parameter "\t\ttest\t\t\t".split(/\t/, -1) => ["", "", "test", "", "", ""]

这在String.split() documentation.中有详细说明