gpt4 book ai didi

ruby-on-rails - Ruby ActiveSupport 数组拆分与字符串拆分

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:20 24 4
gpt4 key购买 nike

"abc def ".split(" ")

返回

["abc", "def"]

因此,我期待:

["a", "b", "c", " ", "d", "e", "f", " "].split(" ")

返回

[["a", "b", "c"], ["d", "e", "f"]]

但它回来了

[["a", "b", "c"], ["d", "e", "f"], []]

我通读了在 active_support/core_ext/array/grouping.rb 中进行拆分的源代码(我正在使用 ActiveSupport 4.0.0 和 ruby​​ 2.0.0-p247)。您可以在此处找到两行文档:http://api.rubyonrails.org/classes/Array.html#method-i-split代码如下:

def split(value = nil, &block)
inject([[]]) do |results, element|
if block && block.call(element) || value == element
results << []
else
results.last << element
end

results
end
end

这解释了它是如何进行拆分的。

现在,这是预期的行为还是 ActiveSupport 错误?

最佳答案

这可能是预期的行为而不是错误。根据文档,拆分数组:

Divides the array into one or more subarrays based on a delimiting value or the result of an optional block.

这不保证连续或前导空格。

另一方面,Ruby core documentation对于 String#split 状态:

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

如您所见,您期望的行为仅适用于空格,不适用于任何字符串。

 "abc ccc def ".split("c")
=> ["ab", " ", "", "", " def "]

拆分数组时,“空格”的概念不再有意义。所以我认为这种行为是明智的,即使一开始可能违反直觉。

关于ruby-on-rails - Ruby ActiveSupport 数组拆分与字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19825976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com