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?
"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))