Parnab Sanyal Parnab Sanyal - 1 year ago 125
Ruby Question

Difficulty understanding optional parentheses

I am having problem understanding the execution in the following code snippet.

x = 5
puts (0..10).include?(x) ? "yes" : "no"

It is giving the desired output which is
. But when I am omitting the parentheses of

method like this :

x = 5
puts (0..10).include? x ? "yes" : "no"

then output is
I am using
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

Answer Source

That is because in the second case ruby takes the result of the whole x ? "yes" : "no" expresion as argument.

 puts (0..10).include? x ? "yes" : "no"

is equivalent to:

 puts (0..10).include?(x ? "yes" : "no")

Ruby allows to omit brackets for method calls, but there are cases, when it's impossible to omit them to write what you've intended.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download