Group_by

>> colors = %w(red orange yellow green blue indigo violet)
=> ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
>> colors.group_by {|color| color.size }
=> {3=>["red"], 6=>["orange", "yellow", "indigo", "violet"],
    5=>["green"], 4=>["blue"]}

Partition

class Person
  attr_accessor :age
  def initialize(options)
    self.age = options[:age]
  end
  def teenager?
    (13..19) === age
  end 
end

# generate an array of people:
people = 10.step(25,3).map {|i| Person.new(:age => i) }
# partition them into teens and non-teens:
partition them into teens and non-teens:

#Result:
[[#<Person:0x000001019d1a50 @age=13>, #<Person:0x000001019d19d8 @age=16>, #<Person:0x000001019d1988 @age=19>], [#<Person:0x000001019d1ac8 @age=10>, #<Person:0x000001019d1910 @age=22>, #<Person:0x000001019d1898 @age=25>]]

#this is an array containing two subarrays. 

artpes57

Author artpes57

More posts by artpes57

Leave a Reply

All rights reserved Salient.