为什么split('')试图变得(太)聪明?

编程入门 行业动态 更新时间:2024-10-25 23:29:36
本文介绍了为什么split('')试图变得(太)聪明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我刚刚发现String#split具有以下奇怪行为:

I just discovered the following odd behavior with String#split:

"a\tb c\nd".split => ["a", "b", "c", "d"] "a\tb c\nd".split(' ') => ["a", "b", "c", "d"] "a\tb c\nd".split(/ /) => ["a\tb", "c\nd"]

源(来自2.0.0的string.c)超过200行很长,包含一段这样的段落:

The source (string.c from 2.0.0) is over 200 lines long and contains a passage like this:

/* L 5909 */ else if (rb_enc_asciicompat(enc2) == 1) { if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' '){ split_type = awk; } }

稍后,在awk拆分类型的代码中,实际的参数甚至不再使用,并且与普通的split相同.

Later, in the code for the awk split type, the actual argument isn't even used any more and does the same as a plain split.

  • 其他人是否认为这已被打破?
  • 这是否有充分的理由?
  • 这样的魔术"发生的频率是否比大多数人在Ruby中想象的还要频繁?
推荐答案

这与Perl的split()行为一致.依次基于 Gnu awk的 split().因此,这是起源于Unix的悠久传统.

It's consistent with Perl's split() behavior. Which in turn is based on Gnu awk's split(). So it's a long-standing tradition with origins in Unix.

在split上的 perldoc 中:

作为另一种特殊情况,split模仿了默认行为 当省略PATTERN或立即输入文字时使用命令行工具awk 由单个空格字符组成的字符串(例如''或"\ x20", 但不是//).在这种情况下,EXPR中的任何前导空格都是 在拆分之前将其删除,然后将PATTERN视为 如果是/\ s +/;特别是,这意味着任何连续的 空格(不只是单个空格字符)用作分隔符. 但是,可以通过指定 模式//代替字符串",从而只允许一个 空格字符作为分隔符.

As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20" , but not e.g. / / ). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/ ; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern / / instead of the string " " , thereby allowing only a single space character to be a separator.

更多推荐

为什么split('')试图变得(太)聪明?

本文发布于:2023-07-19 08:58:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:聪明   split

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!