Last active
August 29, 2015 14:21
-
-
Save aaron-lane/a2b8ba44c9a50bdbf0ac to your computer and use it in GitHub Desktop.
Ruby block precedence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# {} is given higher precedence than do..end by the interpreter | |
def foo a = 'foo', &b | |
b ||= proc { 'foo' } | |
puts b.call.concat a | |
end | |
def bar &b | |
b ||= proc { 'bar' } | |
b.call | |
end | |
foo | |
# foofoo | |
foo bar | |
# foobar | |
foo bar { 'biz' } | |
# foobiz | |
foo bar do 'baz' end | |
# bazbar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I dislike the current rule in the Ruby Style guide that recommends basing the usage of one style or the other on the number of lines in the block because it is so arbitrary. The Weircih method has a lot of value because it encourages a better understanding of the intent of the blocks, but I like the idea of using the two variants based on this behavior because it encourages a better understanding of how the code is evaluated while also providing more flexibility in expressions.
I picked up the strategy of explicit block arguments from Avdi Grimm. I think it's great because it makes the method signature complete, it allows for setting default values, and avoids conditional logic like
if block_passed?
, which is really just a pretty version of nil checking.