Skip to content

Instantly share code, notes, and snippets.

@aaron-lane
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaron-lane/a2b8ba44c9a50bdbf0ac to your computer and use it in GitHub Desktop.
Save aaron-lane/a2b8ba44c9a50bdbf0ac to your computer and use it in GitHub Desktop.
Ruby block precedence
# {} 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
@amaltson
Copy link

Ahhh, interesting. And this furthers your war on parenthesis too? Excellent!

But in all honesty, that does make sense. It's not so much multiline as arguments to functions that also take in blocks.

Btw, is this your new approach of always converting blocks to procs in your method?

@aaron-lane
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment