Ruby Tuesday – Enumerable#partition

Today’s Ruby Tuesday method is Enumerable#partition.

Enumerable#partition takes a block and returns an array of two arrays. The first item in the returned array is an array of items for which the block returns a truthy value. The second item in the returned array are the items for which the block returns a falsey value.

[:a, 1, "b", :c, [1, 2, 3,]].partition{|x| x.is_a? Symbol}
# => [[:a, :c], [1, "b", [1, 2, 3]]]
[1, 2, 3, 4, 5, 6, 7].partition{|x| x.even?}
# => [[2, 4, 6], [1, 3, 5, 7]]
["foo", "snafu", "bar", "hello world"].partition{|x| x.size < 5}
# => [["foo", "bar"], ["snafu", "hello world"]]
["foo", "snafu", "bar", "hello world"].partition{|x| x.size < 15}
# => [["foo", "snafu", "bar", "hello world"], []]
[1, 2, 3, 4].partition{|x| x}
# => [[1, 2, 3, 4], []]
[1, 2, 3, 4].partition{|x| nil}
# => [[], [1, 2, 3, 4]]

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *