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:
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.
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.
The puts
method always returns nil. So when you say puts {}.class
, that's basically the same as puts.class
, which is NilClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With