Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a ternary operator with assignment return the expected output?

I'm wondering why assignment with the ternary operator reacts strangely:

a = "foo"­
=> "foo"
a = nil ? nil : a
=> "foo"
a
=> "foo"

but:

a = nil ? nil : a
=> "foo"
a = "bar"­ ? "bar"­ : a
=> "bar"
a
=> "bar"

and:

if a = nil
  puts "should be nil"
end
=> nil

won't puts the string because a = nil will return nil thus false, although the assignment was successful.

Is that all behaving like intended?

like image 843
jethroo Avatar asked Nov 23 '25 08:11

jethroo


2 Answers

if a = nil

This isn't returning false, it's returning what was assigned, which in this case was nil. nil is 'falsy' so that's why it does not go into the puts

As to why:

a = "foo"­
=> "foo"
a = nil ? nil : a
=> "foo"
a
=> "foo"

It's because you are assigning a again. nil ? nil : a returns a so that's what gets assigned. So a = nil ? nil: a ends up being interpreted like a = a.

like image 135
Dty Avatar answered Nov 25 '25 22:11

Dty


I believe this:

if a = nil

should be:

if a == nil

A single = means assignment, and a = nil is assigning nil to a and evaluating to nil as a result, which is false. That's why the execution doesn't enter the puts part, whereas == means equality testing.

Other than that, what do you find strange in the code? It's normal behavior after all.

like image 41
Óscar López Avatar answered Nov 25 '25 21:11

Óscar López



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!