Ruby ||= Behaviour | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

Ruby ||= Behaviour

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

24th Aug 2019, 11:32 PM
ABADA S
ABADA S - avatar
3 Answers
+ 5
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.
25th Aug 2019, 12:32 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
thanks this is full answer
27th Aug 2019, 2:32 AM
ABADA S
ABADA S - avatar
0
I want an example of Ruby
6th Jun 2021, 12:09 AM
حسين شكر فتحي المولى
حسين شكر فتحي المولى - avatar