+4

Ruby ||= Behaviour

can someone explain this please What is the output of this code? foo = false bar = 2 print foo ||=bar

8/24/2019 11:32:26 PM

ABADA S

2 Answers

New Answer

+4

This one really gave me a full trip. x ||= y actually behaves as x || (x = y) instead of x = (x || y) In short, what this means is that y is assigned to x only if x is falsy. We know that anything which is not false or nil is truthy in Ruby, so in your example, foo (false) is falsy and bar (2) is truthy. foo ||= bar is evaluated as foo || (foo = bar) Since foo is truthy, foo = bar is not executed, and foo is returned from the statement. The value of foo, 2, is printed.

+2

thanks this is full answer