prajeesh
prajeesh

Reputation: 2382

Assign `nil` to multiple variables

I need to assign nil to multiple variables. I have:

a = nil
b = nil
c = nil

Which is the most efficient way to do this?

Upvotes: 1

Views: 1775

Answers (3)

Wand Maker
Wand Maker

Reputation: 18762

You could do the following:

a,b,c = nil,nil,nil
# or
a,b,c = [nil] * 3

You could also do the following which takes the advantage of the fact that default value of variable is nil if not assigned one explicitly.

a,b,c = nil

In above case, the explicit nil will get assigned to a, while b and c will get default nil. Hence, its a trick that will work only for nil.


You can also have all three variables get assigned default nil by using dummy variable _ as first variable in parallel assignment.

_,a,b,c = nil

Upvotes: 5

Sayuj
Sayuj

Reputation: 7622

To assign nil you can use

a = b = c = nil

But remember this works only for immutable objects.

See this example:

a = b = c = "test"
b << "1"
a # => "test1"

There you may need to try:

a, b, c = 3.times.map{ "test" }

Upvotes: 1

AnoE
AnoE

Reputation: 8345

It pretty much won't get any shorter than:

a = b = c = nil

Upvotes: 8

Related Questions