Block or Hash?

Ruby uses curly brackets to delimit both blocks and hashes. So, how can you (and Ruby) tell which is which? The answer, basically, is that it’s a hash when it looks like a hash, and otherwise it’s a block. A hash looks like a hash when curly brackets contain key-value pairs:

puts( {1=>2}.class )     #<= Hash

or when they are empty:

block_or_hash.rb

puts( {}.class )         #<= Hash

However, if you omit the parentheses, there is an ambiguity. Is this an empty hash, or is it a block associated with the puts method?

puts{}.class

Frankly, I have to admit I don’t know the answer to that question, and I can’t get Ruby to tell me. Ruby accepts this as valid syntax but does not, in fact, display anything when the code executes. So, how about this?

print{}.class ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.