我刚刚发现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('')试图变得(太)聪明?
发布评论