Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the expression "a, b = 5" set a to 5, but b to nil in Ruby?

(irb) a, b = 5
a => 5
b => nil

Shouldn't that be the other way around? What is actually happening here?

like image 201
Monti Avatar asked Jul 16 '15 18:07

Monti


2 Answers

As I was writing this my coworker discovered why:

Ruby treats a, b = 5 as a, b = 5, nil

In Python3, a TypeError is thrown.

like image 187
Monti Avatar answered Sep 20 '22 16:09

Monti


In order to assign a value to b using multiple assignment you'd have to give it a second value.

a, b = 5, 6

a = 5
b = 6

When you don't supply a second value, Ruby gives b a value of nil

like image 22
nextstep Avatar answered Sep 18 '22 16:09

nextstep