Ruby Enumerable#partition

More than once in the past I would have used this, had I known it was there. Often I am consumed by the task of getting the job done and less focussed on keeping up to date with the documentation. Using partition you can split objects into two groups fairly easily. In this example, I’ll take two use cases for it. The first one is simply a way to understand it well, while the second will be a possible usage scenario.

Here, we will take a finite number, 10 and split it into a set of even and odd numbers. We will assign them to the respective variables, odd and even. I am doing this in IRB, which will show you the version of Ruby that I am executing in:

ruby-1.9.2-p180 :001 > odd, even = 10.times.partition { |x| x % 2 == 1 }
 => [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]
ruby-1.9.2-p180 :002 > odd
 => [1, 3, 5, 7, 9]
ruby-1.9.2-p180 :003 > even
 => [0, 2, 4, 6, 8]
ruby-1.9.2-p180 :004 >

Now let’s take a quick look at using this with an Object:

  1. Add the class
  2. ruby-1.9.2-p180 :005 > class Person
    ruby-1.9.2-p180 :006?>   attr :sex
    ruby-1.9.2-p180 :007?>   def initialize( sex = "f" )
    ruby-1.9.2-p180 :008?>     @sex = sex
    ruby-1.9.2-p180 :009?>     end
    ruby-1.9.2-p180 :010?>   end
     => nil
    
  3. Add some Person objects to our people array
  4. ruby-1.9.2-p180 :013 > people = []
     => []
    ruby-1.9.2-p180 :014 > people << Person.new("m")
     => [#<Person:0x000001013084d0 @sex="m">]
    ruby-1.9.2-p180 :015 > people << Person.new("m")
     => [#<Person:0x000001013084d0 @sex="m">, #<Person:0x000001012fc018 @sex="m">]
    ruby-1.9.2-p180 :016 > people << Person.new
     => [#<Person:0x000001013084d0 @sex="m">, #<Person:0x000001012fc018 @sex="m">, #<Person:0x000001012f7810 @sex="f">]
    
  5. Partition our people based on sex
  6. ruby-1.9.2-p180 :017 > men, women = people.partition { |p| p.sex == "m" }
     => [[#<Person:0x000001013084d0 @sex="m">, #<Person:0x000001012fc018 @sex="m">], [#<Person:0x000001012f7810 @sex="f">]]
    ruby-1.9.2-p180 :018 > men
     => [#<Person:0x000001013084d0 @sex="m">, #<Person:0x000001012fc018 @sex="m">]
    ruby-1.9.2-p180 :019 > women
     => [#<Person:0x000001012f7810 @sex="f">]
    ruby-1.9.2-p180 :020 >
    

    This is a fairly easy demonstration of Enumerable#partition, and if you’re like me, once you see it, you’ll never forget it. It’s a fun one to work with for sure!

Tags: ,

About the Author: JeffAncel
http://jeffancel.com
A passionate web developer in St. Louis. Living on the edge with Rails, HTML5, CSS3 and any interesting libraries around. I love to spend time with the family, cook, develop web applications and play with our dragons. When I have nothing else to do, I socialize via twitter (@jancel) and facebook.

Leave a reply

© 2012 - Jeff Ancel
Wordpress Themes
Scroll to Top