# 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
Asked
Active
Viewed 1,812 times
10

house9
- 20,359
- 8
- 55
- 61
-
Built in methods are nice, but are you opposed to adding your own method to `Array` that would do this? – MrDanA Apr 05 '13 at 23:47
-
yes, i was thinking about monkey patching Array to add it - seems like something ruby might already have built in, but didn't see anything in the docs – house9 Apr 05 '13 at 23:50
4 Answers
20
Sure, you can do:
odd, even = list.partition &:odd?

pguardiario
- 53,827
- 19
- 119
- 159
-
awesome - thanks; interesting it shows up on the enumerable docs - http://ruby-doc.org/core-1.9.2/Enumerable.html but not on array? – house9 Apr 05 '13 at 23:59
-
1@house9 Enumerable is a mixin, so many classes can use it. Hashes use them too. – MrDanA Apr 06 '13 at 04:57
-
That's because it is defined on `Enumerable` but not on `Array`. This is called *inheritance* and is one of the fundamental concepts of Ruby and many other languages, not just object-oriented ones. – Jörg W Mittag Apr 06 '13 at 07:51
1
odd = []
even = []
list = [1..20]
list.each {|x| x.odd? ? odd << x : even << x }

duggiefresh
- 283
- 1
- 8
1
As pguardiario said, the partition
method is the most direct way. You could also use Set#divide
:
require 'set'
list = (1..10).to_a
odd, even = Set.new(list).divide(&:odd?).to_a.map{|x| x.to_a}

alf
- 18,372
- 10
- 61
- 92
1
You could try below:
odd,even = (0..20).group_by(&:odd?).values
p odd,even
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Arup Rakshit
- 116,827
- 30
- 260
- 317