everything and nothing

allskonar

I finally found an opportunity to use ruby partition method. It splits an array you have upon a criteria you supply in a block. Typically, in the old days, I would have done this by doing something like this:


big_array = Array.new(11) {|i| i}
number_lower_than_5 = []

big_array.each do |number|
  if number < 5 
    number_lower_than_5 << number
  end 
end

# >> number_lower_than_5
# => [0,1,2,3,4]

or more recently I would use select


big_array = Array.new(11) {|i| i}
number_lower_than_5 = []

number_lower_than_5 = 
big_array.select do |number|
  number < 5 
end

# >> number_lower_than_5
# => [0,1,2,3,4]

These are both fine methods but what happens if you need the other halve as well? The above approaches just collect you an array to work with and both lack the convenient array of the other stuff you sometimes care about. That’s where ruby’s partition comes in handy. It may not be that often that’s why I was so pumped up when I found an opportunity to use it.


big_array = Array.new(11) {|i| i}
number_lower_than_5, the_rest =
big_array.partition do |number|
  number < 5 
end

# >> number_lower_than_5
# => [0,1,2,3,4]
# >> the_rest
# => [5,6,7,8,9,10]

When needed the partition method can be very convenient

Sorry, comments are closed for this article.

Freyja Channel


last.fm recent tracks

allskonar Powered by Mephisto