When you type:
(5 + 5)
it’s evaluated first.
When you type:
puts (5 + 5)
literally the same thing happens. You pass 10 to puts.
But when you type:
puts (5, 5)
, Ruby raises SyntaxError
because it can’t be evaluated… It’s like writing 5, 5
without any method name. Ruby doesn’t know that it’s passed to the method call.
You can either do puts 5, 5
or do puts(5, 5)
. Both will work the same way. For method chaining though:
puts 5.class # => nil (and writes Integer to STDOUT)
puts(5).class # => NilClass (and writes 5 to STDOUT)
puts (5).class # => nil (and writes Integer to STDOUT)
On the first line, we are calling 5.class
first, which returns Integer
, which is then passed to Kernel#puts
which prints Integer
and returns nil
.
On the second line, we are calling Kernel#puts
with 5
, which displays 5
, and returns nil
. That’s why the second line returns NilClass
because it’s like running nil.class
.
On the third line, when we write (5)
it returns 5
, which is an Integer
object. We then call the class
method on 5
, which obviously returns Integer
. We are then passing this to the Kernel#puts
, which writes Integer
to the standard output, and returns nil
.
Another example which might help:
puts(5 + 5 / 2) # => 7
puts(5.+(5)./(2)) # => 5
puts((5 + 5) / 2) # => 5
And that’s the reason my friend you get SyntaxError when you write additioner (x, y) puts (x * y)
in your code…
Hope this helps!