思考这个:
x = [] # => []
input = '1 2 3' # => "1 2 3"
x.push input # => ["1 2 3"]
x.sort # => ["1 2 3"]
基本上,您在代码中输入单个字符串,将其推入数组,然后对单个元素数组进行排序。这不会做任何事情,因为您无法对单个元素数组进行排序并获得不同的顺序。 (嗯,你可以期待它会有所不同,但事实并非如此。)
改为:
x = [] # => []
x.push '1' # => ["1"]
x.push '3' # => ["1", "3"]
x.push '2' # => ["1", "3", "2"]
模拟输入三个不同的字符串。排序x 现在返回一个排序数组:
x.sort # => ["1", "2", "3"]
这里还有一些值得思考的事情:
require 'fruity'
string = ('a'..'z').to_a.join(' ')
string # => "a b c d e f g h i j k l m n o p q r s t u v w x y z"
3.times do
compare do
split1 { string.split }
split2 { string.split(' ') }
split3 { string.split(/\s/) }
split4 { string.split(/\s+/) }
end
end
# >> Running each test 1024 times. Test will take about 1 second.
# >> split1 is faster than split2 by 10.000000000000009% ± 10.0%
# >> split2 is faster than split3 by 3x ± 0.1
# >> split3 is similar to split4
# >> Running each test 2048 times. Test will take about 1 second.
# >> split1 is faster than split2 by 10.000000000000009% ± 10.0%
# >> split2 is faster than split3 by 3x ± 0.1
# >> split3 is similar to split4
# >> Running each test 1024 times. Test will take about 1 second.
# >> split1 is faster than split2 by 10.000000000000009% ± 10.0%
# >> split2 is faster than split3 by 3x ± 0.1
# >> split3 is similar to split4
split1 和 split2 的结果大约有 10% 支持 split1,因此,Fruity 有时会报告 10% 的差异,有时则不会。 split3 和 split4 也是如此。
还有:
string = ('a'..'z').to_a.zip(26.times.map{ ' ' * (rand(4) + 1)}).join
string # => "a b c d e f g h i j k l m n o p q r s t u v w x y z "
compare do
split1 { string.split }
split2 { string.split(' ') }
split3 { string.split(/\s/) }
split4 { string.split(/\s+/) }
end
# >> Running each test 1024 times. Test will take about 1 second.
# >> split1 is similar to split2
# >> split2 is faster than split4 by 3x ± 0.1
# >> split4 is faster than split3 by 2.1x ± 0.1 (results differ: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] vs ["a", "", "", "", "b", "", "c", "", "", "", "d", "", "", "", "e", "", "f", "", "", "g", "", "h", "", "", "i", "j", "", "k", "l", "", "m", "", "", "", "n", "", "o", "", "p", "q", "r", "", "", "", "s", "", "", "t", "", "", "u", "", "v", "w", "", "x", "", "", "", "y", "z"])
最后一个结果是不同的,因为split(/\s/) 只寻找单个空白字符,而不是像split(/\s+/) 那样的倍数。我留下这个结果是为了展示 + 对引擎的影响。