在拆分字符串时,Ruby 中的#split 和#chars 有什么区别?
"Hello, World".split("")
#=> ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
"Hello, World".chars
#=> ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
它们都返回一个数组,并且都包含空格和标点符号。
有没有一种情况更可取?
最佳答案
What is the difference between
split
andchars
[...]?
string.chars
解析底层字节以返回字符串的字符,而 string.split('')
使用正则表达式来实现相同的目的。
因此,chars
更快、更健壮。如果字符串包含无效字符,它甚至可以工作:
"foo\x80bar".chars
#=> ["f", "o", "o", "\x80", "b", "a", "r"]
而如果字符串格式错误(因为正则表达式引擎无法处理),split
会失败:
"foo\x80bar".split('')
#=> ArgumentError: invalid byte sequence in UTF-8
如果我没记错的话,split('')
等同于 split(//)
。
Is there a scenario where one is preferable?
split('')
可以在很多教程中找到。我认为这是因为在 Ruby 2.x 之前,chars
返回了一个枚举器。因此,为了获得一个数组,您必须使用两个 方法调用:
string.chars.to_a
或一次调用:(也略短)
string.split('')
如今,您将使用 chars
(或 each_char
用于 2.x 之前的行为)
关于Ruby #split ("") 与字符串上的#chars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46436825/