July 2011
Intermediate to advanced
400 pages
8h 46m
English
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 ) #<= Hashor when they are empty:
block_or_hash.rb
puts( {}.class ) #<= HashHowever, 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{}.classFrankly, 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 ...Read now
Unlock full access