diff --git a/README.md b/README.md index 75ee687..2c7c744 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ _323 TILs and counting..._ - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) - [Identify Outdated Gems](ruby/identify-outdated-gems.md) +- [If You Detect None](ruby/if-you-detect-none.md) - [Invoking Rake Tasks Multiple Times](ruby/invoking-rake-tasks-multiple-times.md) - [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md) - [Limit Split](ruby/limit-split.md) diff --git a/ruby/if-you-detect-none.md b/ruby/if-you-detect-none.md new file mode 100644 index 0000000..423d645 --- /dev/null +++ b/ruby/if-you-detect-none.md @@ -0,0 +1,33 @@ +# If You Detect None + +The +[`Enumerable#detect`](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-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. + +```ruby +# 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: + +```ruby +> [2,4,6,8].detect(->{0}, &:odd?) +=> 0 +``` + +And if you want to be really explicit: + +```ruby +> [2,4,6,8].detect(ifnone=->{0}, &:odd?) +=> 0 +```