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
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
Once again, this prints nothing at all in Ruby 1.9, but in Ruby 1.8 it displays nil
(not, you will notice, the actual class of nil
, which is NilClass, but nil
itself). If you find all this confusing (as I do!), just remember that this can all be clarified by the judicious use of parentheses:
print( {}.class ) #<= Hash
3.133.159.223