Ruby Tuesday – Enumerable#select

Today’s Ruby Tuesday is on Enumerable#select.

Enumerable#select iterates over a list, passing each element to the provided block, and returns an array of those items for which the block returns a truthy value.

[1, 2, 3, 4, 5].select &:even?
# => [2, 4]
[1, 2, 3, 4, 5].select {|item| item.even?}
# => [2, 4]
["a", "foo", "snafu", "rb", "qwerty"].select {|item| item.length > 3}
# => ["snafu", "qwerty"]

If no items are found to meet the criteria, Enumerable#select returns an empty array.

[1, 2, 3, 4, 5].select {|item| item > 25 }
# => []

Enumerable#reject

Enumerable#select has a counterpart of Enumerable#reject which returns an array of items for which the block returns a falsey value.

[1, 2, 3, 4, 5].reject &:even?
# => [1, 3, 5] 
[1, 2, 3, 4, 5].reject {|item| item.even?}
# => [1, 3, 5]
["a", "foo", "snafu", "rb", "qwerty"].reject {|item| item.length > 3}
# => ["a", "foo", "rb"]

If all items are found to meet the criteria, Enumerable#reject returns an empty array.

[1, 2, 3, 4, 5].reject {|item| item > 0 }
# => []

–Proctor

1 thought on “Ruby Tuesday – Enumerable#select

  1. Pingback: Ruby Tuesday – Enumerable#drop_whileProctor It | Proctor It

Comments are closed.