简体   繁体   中英

Unexpected behaviour in Ruby for “puts {}.class”

puts {}.class

#=> NilClass 

puts "".class
String
#=> nil 

puts [].class
Array
#=> nil

Why is puts {}.class not showing Hash as output and then nil like the others?

puts {} is interpreted as puts method call with empty block passed into it, hence the empty result. puts({}.class) works as you expect.

There are a couple things to understand:

  1. whenever a hash is the first argument to a method being called, you need to use parenthesis or remove the braces, otherwise ruby thinks it's a block. So puts { foo: "bar" } raises a syntax error, but puts foo: "bar" , puts(foo: "bar") , or puts({foo: "bar"}) work fine.

  2. every method can be called with a block, however only some methods actually call the block. You can test it for yourself - puts(1) { raise } just outputs the number, and doesn't raise an error. puts { 1 } prints nothing, because the block isn't called.

  3. The puts method always returns nil. So when you say puts {}.class , that's basically the same as puts.class , which is NilClass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM