Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty understanding optional parentheses

Tags:

ruby

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 yes. But when I am omitting the parentheses of include? method like this :

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

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

like image 626
Parnab Sanyal Avatar asked Apr 09 '26 08:04

Parnab Sanyal


1 Answers

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.

like image 90
maicher Avatar answered Apr 10 '26 23:04

maicher



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!