Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

akward ternary evaluation in ruby

I'm very confused about some ternary expression in ruby.

I have this expression:

puts respond_to? "greeting".to_sym ? "hello" : "bye"

of course, that isn't what i'm doing in my app, is just for you to see.

the thing is that the above expression returns

false

when it should be returning hello if the method exists and bye if it don't right?

if i change the expression to

puts respond_to?("greeting".to_sym) ? "hello" : "bye"

it returns the right thing, either "hello" if it exists and "bye" otherwise.

Why is this happening? Is there something about ternary expression in ruby that i don't know?

Just for you to know the right code in my app is:

respond_to?(path.to_sym) ? self.send(path) : "#"

Which returns the right path for the db stored header menus and if it don't exists, it will simply put an "#" to avoid errors.

like image 488
JGutierrezC Avatar asked May 08 '26 16:05

JGutierrezC


2 Answers

Without the parentheses, it seems your code is being interpreted like this:

puts respond_to?("greeting".to_sym ? "hello" : "bye")

The stuff in the parenthesis is then evaluating to "hello", and self apparently doesn't respond to that, so respond_to? returns false.

This is why it's always a good idea to use parentheses whenever there's any doubt about the order of operations of your code; it makes your code more readable and eliminates mistakes such as this one.

like image 151
Ajedi32 Avatar answered May 11 '26 07:05

Ajedi32


If you don't have the parenthesis for respond_to, the evaluation happens like this

"greeting".to_sym ? "hello" : "bye" #results in "hello"

puts respond_to? "hello" #results in false

ternary expression will get evaluated first without the parenthesis for respond_to

like image 39
usha Avatar answered May 11 '26 08:05

usha



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!