Why is if (a,b = [nil, nil]) truthy in Ruby?

Viewed 68

I'm studying Ruby now, and I don't understand why the test condition

if (a,b = [nil, nil]) # <--
  true
else
  false
end

evaluates as truthy, while

if (a,b = nil) # <--
  true
else
  false
end

is falsy as advertised.

Tested on ruby 2.5 and 2.7 via irb. Added a complete if-else statement for your copy-paste testing.

2 Answers

Assignments evaluate to the same value as the right operand of the assignment. This is still true for destructuring assignments.

So a,b = [nil, nil] evaluates to [nil, nil], which truthy because it's an array and arrays are truthy, whereas a,b = nil evaluates to nil, which is falsy.

In ruby, only 2 values are false, which are nil and false itself.

All other values are truth, including arrays of nils.

Also, assign operation returns right side of assignment, so

(a,b = [nil, nil]) == [nil, nil]
(a,b = nil) == nil
Related