diff --git a/README.md b/README.md index c3f724e..6ddd23e 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/fetch-warns-about-superseding-block-argument.md b/ruby/fetch-warns-about-superseding-block-argument.md new file mode 100644 index 0000000..58c52b5 --- /dev/null +++ b/ruby/fetch-warns-about-superseding-block-argument.md @@ -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".