Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour in Ruby for "puts {}.class"

Tags:

ruby

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?

like image 245
MEENAKSHI KUMARI Avatar asked Jan 31 '18 07:01

MEENAKSHI KUMARI


2 Answers

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

like image 71
Marek Lipka Avatar answered Nov 02 '22 07:11

Marek Lipka


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

like image 15
max pleaner Avatar answered Nov 02 '22 08:11

max pleaner