Mark Tabler
Mark Tabler

Reputation: 1429

Is there a method in Ruby that divides an array into two smaller arrays based on a logical condition?

Let's say I have a list of elements in an array, but there is a logical way to divide them into two groups. I want to put those elements into two smaller arrays based on that criteria. Here is some code that works and helps illustrate what I mean:

foo = ['a', 'bb', 'c', 'ddd', 'ee', 'f']
 => ["a", "bb", "c", "ddd", "ee", "f"] 
a = foo.select{|element| element.length == 1}
 => ["a", "c", "f"]
b = foo.reject{|element| element.length == 1}
 => ["bb", "ddd", "ee"]

I seem to remember seeing some way by which a single method call would assign both a and b, but I don't remember what it was. It would look something like

matching, non_matching = foo.mystery_method{|element| element.length == 1}

Am I crazy, or does such a method exist in Ruby and/or Rails?

Upvotes: 2

Views: 1018

Answers (1)

Robin
Robin

Reputation: 21884

Yes! http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-partition

matching, non_matching = foo.partition {|element| element.length == 1}

Upvotes: 14

Related Questions