只是一些更多的解决方案扔到池:
x = [1,2,3,"a","b",4]
numbers = x.select{ |e| e.is_a?(Fixnum) } # => [1, 2, 3, 4]
letters = x - numbers # => ["a", "b"]
numbers = x.select{ |e| e.kind_of?(Fixnum) } # => [1, 2, 3, 4]
letters = x - numbers # => ["a", "b"]
或
(numbers, letters) = x.group_by {|a| a.class}.values_at(Fixnum, String)
numbers # => [1, 2, 3, 4]
letters # => ["a", "b"]
随着一些基准测试显示如何了微妙的变化影响速度:
require 'benchmark'
x = [1,2,3,"a","b",4] * 100
n = 10_000
Benchmark.bm do |bench|
bench.report { n.times {
numbers = x.select{ |e| e.is_a?(Fixnum) }
letters = x - numbers
}}
bench.report { n.times {
numbers = x.select{ |e| e.kind_of?(Fixnum) }
letters = x - numbers
}}
bench.report { n.times {
(numbers, letters) = x.group_by {|a| a.class}.values_at(Fixnum, String)
}}
bench.report { n.times {
numbers, not_numbers = x.partition{|item| item.kind_of? Fixnum}
}}
end
# >> user system total real
# >> 4.270000 0.010000 4.280000 ( 4.282922)
# >> 4.290000 0.000000 4.290000 ( 4.288720)
# >> 5.160000 0.010000 5.170000 ( 5.163695)
# >> 3.720000 0.000000 3.720000 ( 3.721459)
+ 1为单线和双重任务。看起来不错。 – slhck 2011-04-16 12:45:47
+1这对于速度来说也是一个可靠的胜利!查看我添加的基准。 – 2011-04-17 04:16:47
下面的答案使用'group_by',它允许分成两个以上的组。 – 2013-10-26 04:02:05