iliketocode alot
iliketocode alot

Reputation: 13

Why does `puts {}.class.name` return nothing in Ruby?

I've tried this with other classes and they return things. Just this one doesn't.

puts ''.class.name # String
puts 1.class.name  # Integer
puts [].class.name # Array
puts {}.class.name

but {}.class.name just returns blank.

Upvotes: 1

Views: 72

Answers (2)

Schwern
Schwern

Reputation: 165208

Because puts {} passes a block.

Any method can take a block.

puts {}.class.name is really (puts {}).class.name. puts {} ignores the block and prints a newline. It returns nil. class.name is called on nil so the return value is NilClass. But that doesn't get passed to puts so it's not printed.

We can see it in IRB.

> puts {}.class.name

 => "NilClass" 

Use parens to clarify. puts({}.class.name).

Upvotes: 4

Lindydancer
Lindydancer

Reputation: 26124

It's because {} is interpreted as a block sent to puts.

class.name is executed when puts returns, and the value is discarded.

Upvotes: 3

Related Questions