Skip to content

Commit c50dca3

Browse files
committed
Add If You Detect None as a ruby til
1 parent a9ae2fa commit c50dca3

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ _323 TILs and counting..._
230230
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
231231
- [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md)
232232
- [Identify Outdated Gems](ruby/identify-outdated-gems.md)
233+
- [If You Detect None](ruby/if-you-detect-none.md)
233234
- [Invoking Rake Tasks Multiple Times](ruby/invoking-rake-tasks-multiple-times.md)
234235
- [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md)
235236
- [Limit Split](ruby/limit-split.md)

ruby/if-you-detect-none.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# If You Detect None
2+
3+
The
4+
[`Enumerable#detect`](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-detect)
5+
method, which is synonymous with `#find`, can be given an optional argument,
6+
`ifnone`, that is called when nothing in the array meets the conditional in
7+
the block. Though I am not sure how this is practically useful and cannot
8+
find an example of it in use, this contrived example illustrates how it
9+
works.
10+
11+
```ruby
12+
# without the fallback behavior
13+
> [2,4,6,8].detect { |x| x.odd? }
14+
=> nil
15+
16+
# with a proc as an argument
17+
> [2,4,6,8].detect(->{0}) { |x| x.odd? }
18+
=> 0
19+
```
20+
21+
The last example can also be written as:
22+
23+
```ruby
24+
> [2,4,6,8].detect(->{0}, &:odd?)
25+
=> 0
26+
```
27+
28+
And if you want to be really explicit:
29+
30+
```ruby
31+
> [2,4,6,8].detect(ifnone=->{0}, &:odd?)
32+
=> 0
33+
```

0 commit comments

Comments
 (0)