If I write
puts 10 - 5
gives 5, same as
puts(10 -5)
Now if I write
puts(- 5)
#gives -5
But if I try -
puts - 5
#NoMethodError: undefined method `-’ for nil:NilClass
It seems, puts - 5 is parsed as (puts) - 5.
But why not are we allowed to write the unary operation with puts
like we are allowed with binary one ?
Regards,
Arup R.
The topic was already discussed here
https://www.ruby-forum.com/topic/207933
The parser needs to decide whether an operator is binary or unary. As it
not yet incorporates A.I. conditions have to be unambiguous and space
before an argument (or lack of it) helps parser in decision. Enclosing
in parentheses enforces associativity so an extra space is ignored.
On Mon, Jul 28, 2014 at 9:34 AM, Arup R.
[email protected] wrote:
But if I try -
puts - 5
NoMethodError: undefined method `-’ for nil:NilClass
It seems, puts - 5 is parsed as (puts) - 5.
But why not are we allowed to write the unary operation with puts
like
we are allowed with binary one ?
Because the parser needs a way to make a decision about ambiguous
syntax to remove ambiguity. The expression “puts - 5” parses the same
as “expr1 - expr2”, i.e. a binary minus expression. There is really no
other way to interpret that without sacrificing consistency.
Kind regards
robert