2013-04-05 30 views
7
# this code works 
list = (0..20).to_a 
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] 

odd = list.select { |x| x.odd? } 
# => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 

list.reject! { |x| x.odd? } 
# => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 

# but can i emulate this type of functionality with an enumerable method? 
set = [1,5,10] 
# => [1, 5, 10] 
one, five, ten = set 
# => [1, 5, 10] 
one 
# => 1 
five 
# => 5 
ten 
# => 10 

# ------------------------------------------------ 
# method I am looking for ? 
list = (0..20).to_a 
odd, even = list.select_with_reject { |x| x.odd? } 
# put the matching items into the first variable 
# and the non-matching into the second 
+0

内置的方法很不错,但你不是添加自己的方法到'数组'这将做到这一点? – MrDanA 2013-04-05 23:47:49

+0

是的,我正在考虑猴子修补阵列来添加它 - 看起来像红宝石可能已经内置的东西,但没有看到任何文档 – house9 2013-04-05 23:50:33

回答

11

当然,可以这样做:

odd, even = list.partition &:odd? 
+0

真棒 - 谢谢;有趣的是它显示在可枚举的文档上 - http://ruby-doc.org/core-1.9.2/Enumerable.html但不在数组上? – house9 2013-04-05 23:59:53

+1

@ house9 Enumerable是一个混合类,所以很多类都可以使用它。哈希也使用它们。 – MrDanA 2013-04-06 04:57:02

+0

这是因为它是在'Enumerable'上定义的,而不是在'Array'上定义的。这被称为* inheritance *,是Ruby和许多其他语言的基本概念之一,而不仅仅是面向对象的概念。 – 2013-04-06 07:51:52

1
odd = [] 
even = [] 
list = [1..20] 
list.each {|x| x.odd? ? odd << x : even << x } 
0

正如pguardiario所说,partition方法是最直接的方式。你也可以使用Set#divide

require 'set' 
list = (1..10).to_a 
odd, even = Set.new(list).divide(&:odd?).to_a.map{|x| x.to_a} 
0

你可以尝试以下:

odd,even = (0..20).group_by(&:odd?).values 
p odd,even 

输出:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]