Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does () returns nil in Ruby?

In Ruby, when you run:

()
=> nil

The output is nil. I don't understand which Ruby mechanism this is using.

I thought it was calling self(), but self() returns syntax error, unexpected '(', expecting end-of-input.

Why does this return nil, and which language feature is this using?

like image 699
Vinicius Brasil Avatar asked Feb 10 '26 20:02

Vinicius Brasil


1 Answers

"No value" is treated as nil in very many places in Ruby:

-> { break }.()
#⇒ nil

42 if false
#⇒ nil

The same is here: parentheses are redundant but they maintain the code block, the empty one, hence it’s treated as nil.


With Ruby 2.6+ you might check the AST yourself:

main > RubyVM::AbstractSyntaxTree.parse('()')
#⇒ (SCOPE@1:0-1:2 tbl: [] args: nil body: (BEGIN@1:1-1:1 nil))
like image 184
Aleksei Matiushkin Avatar answered Feb 15 '26 07:02

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!