From b329d36888430bb2190643fcd2b1a4713dc12592 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 28 Nov 2024 14:06:07 -0600 Subject: [PATCH] Add Block Syntaxes Have Different Precedence as a Ruby TIL --- README.md | 3 +- ...lock-syntaxes-have-different-precedence.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 ruby/block-syntaxes-have-different-precedence.md diff --git a/README.md b/README.md index 1e908ab..cbaa46d 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). -_1519 TILs and counting..._ +_1520 TILs and counting..._ --- @@ -1188,6 +1188,7 @@ _1519 TILs and counting..._ - [Audit Your Ruby Project For Any CVEs](ruby/audit-your-ruby-project-for-any-cves.md) - [Assoc For Hashes](ruby/assoc-for-hashes.md) - [Block Comments](ruby/block-comments.md) +- [Block Syntaxes Have Different Precedence](ruby/block-syntaxes-have-different-precedence.md) - [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md) - [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md) - [Check For Any Overlaps In List Of Ranges](ruby/check-for-any-overlaps-in-list-of-ranges.md) diff --git a/ruby/block-syntaxes-have-different-precedence.md b/ruby/block-syntaxes-have-different-precedence.md new file mode 100644 index 0000000..c7e641a --- /dev/null +++ b/ruby/block-syntaxes-have-different-precedence.md @@ -0,0 +1,29 @@ +# Block Syntaxes Have Different Precedence + +There are two syntaxes for defining a block in Ruby. The semantically shorthand +syntax uses the curly braces (`{}`). The semantically multi-line syntax uses +`do` and `end`. For nearly all intents and purposes they are interchangable. + +It is, however, worth noting that the `do`/`end` version has a lower precedence +than the already low precedence of `{}`. That said, you have to write some +weird code for this to become an issue. + +Let's say we have two methods, `method_one` and `method_two`. They are both +called on the same line like below and then followed by a block argument. Which +method receives the block argument? + +```ruby +method_one method_two { |n| + puts "Executing a block: #{n}" +} + +method_one method_two do |n| + puts "Executing a block: #{n}" +end +``` + +In the first case, with the curly braces, `method_two` receives the block as an +argument. In the second case, with the `do`/`end`, `method_one` receives the +block as an argument. + +[source](http://localhost:3131/ruby-operators/curly-braces#block-shorthand)