Reputation: 2382
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
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
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