MEENAKSHI KUMARI
MEENAKSHI KUMARI

Reputation: 191

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?

Upvotes: 15

Views: 723

Answers (2)

max pleaner
max pleaner

Reputation: 26778

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

Upvotes: 15

Marek Lipka
Marek Lipka

Reputation: 51171

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

Upvotes: 21

Related Questions