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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With