Hacker News new | ask | show | jobs
by dlisboa 3619 days ago
Haven't tried it, but the assignment semantics is that the return of the assignment expression is always the right hand side of the operator. They probably kept that semantic. So

  foo, bar = ['foo', nil]
evaluates to

   ['foo', nil]
which is truthy.

If the code was:

  if (foo, bar = [nil, nil])
    'truthy'
  else
    'falsey'
  end
It'd still be truthy even if no variables were "set" (they were actually set, explicitly to nil, but you get the idea) because [nil, nil] is truthy. It doesn't have anything to do with the values of the variables after the assignment, just what's on the right hand side.
1 comments

Interesting. In particular the result with both values being nil is something I would find pretty counter-intuitive.
Just gotta remember there's nothing special about there being an assignment there, it's just another expression. `if` is another expression and it doesn't care about the status of assignments or whatever is in the conditional clause, only what the expression inside evaluates to.

As far as the assignment operator evaluating to the right hand side, it'd be more difficult to understand if that wasn't the case. There are more scenarios to destructuring on the left hand side than the right.

Also keep in mind there's no such thing as a "failed" assignment. They always work, sometimes things are just assigned to nil explicitly or implicitly.

This case is somewhat hard to get because it brings together a few things of Ruby in way that can get weird. Those things separately are actually pretty good, but bunched up makes it a bit more dense semantically. Which is why it's best to avoid getting too clever with assignments in conditionals.