1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Fetch Warns About Superseding Block Argument as a Ruby TIL

This commit is contained in:
jbranchaud
2023-03-03 10:35:39 -06:00
parent 12178cf153
commit 5a72dcfb95
2 changed files with 31 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1288 TILs and counting..._
_1289 TILs and counting..._
---
@@ -1043,6 +1043,7 @@ _1288 TILs and counting..._
- [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md)
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
- [Fail](ruby/fail.md)
- [Fetch Warns About Superseding Block Argument](ruby/fetch-warns-about-superseding-block-argument.md)
- [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md)
- [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md)
- [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md)

View File

@@ -0,0 +1,29 @@
# Fetch Warns About Superseding Block Argument
[Ruby's `#fetch`](https://ruby-doc.org/core-2.5.1/Hash.html#method-i-fetch) can
be used in a couple ways beyond just grabbing the value out of a hash.
If you include a second argument in the `#fetch` call, that will be treated as
a default value to fallback to when the first argument key doesn't appear in
the hash.
If you instead specify a block argument, that block will be executed when the
key is missing.
What happens when you specify both a second argument and a block argument?
```ruby
data = { taco: 'bell' }
data.fetch(:burrito, 'house') do
puts 'the block gets executed'
'shack'
end
warning: block supersedes default value argument
the block gets executed
=> 'shack'
```
The block argument wins. The second argument is ignored. And Ruby warns you
that, "block supersedes default value argument".