Ruby enumerable: select
This course covers Ruby's select method and the methods around it. It shows how select keeps elements where the block is truthy, returns a new collection of any length, and leaves the original untouched. It compares select with map and each, introduces reject as its opposite, and explains the filter alias and how select on a hash returns a hash. It covers select! and its nil return value, then tours any?, all?, none?, count and find. A final challenge combines these in an order status checker.
What you'll learn
- ✓Filtering arrays with select and Ruby's truthy and falsy rules
- ✓Choosing between each, map and select from what the code needs back
- ✓Using reject to avoid a negated condition
- ✓Using filter and select on hashes, which return a hash
- ✓Why select! and reject! return nil when nothing is removed
- ✓Using any?, all?, none?, count and find
select filters elements
Lesson 6 of the last course ended on a pitfall: map can't skip an element, even when the block's logic looks like it should. select is built for that job.
Read the full lesson free →Curriculum
7 lessonsselect filters elements
select keeps elements where the block is truthy, returns a new array, and may return an empty one.
select vs map vs each
Compares each, map and select, and shows filtering with select before transforming with map.
reject: the opposite of select
reject keeps elements where the block is falsy, and choosing it can avoid a leading exclamation mark.
filter and select on hashes
filter is an alias for select, and select or reject on a hash returns a hash.
select! and its real gotcha
select! filters in place but returns nil when nothing was removed, so read the original variable.
Related Enumerable methods
A tour of any?, all?, none?, count and find, which answer questions without building a filtered array.
Putting it together: a small challenge
An order status checker combines select, an empty-result guard, count, any? and first in one method.