Today I Learned

hashrocket A Hashrocket project

If You Detect None

The Enumerable#detect method, which is synonymous with #find, can be given an optional argument, ifnone, that is called when nothing in the array meets the conditional in the block. Though I am not sure how this is practically useful and cannot find an example of it in use, this contrived example illustrates how it works.

# without the fallback behavior
> [2,4,6,8].detect { |x| x.odd? }
=> nil

# with a proc as an argument
> [2,4,6,8].detect(->{0}) { |x| x.odd? }
=> 0

The last example can also be written as:

> [2,4,6,8].detect(->{0}, &:odd?)
=> 0

And if you want to be really explicit:

> [2,4,6,8].detect(ifnone=->{0}, &:odd?)
=> 0
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.