Reputation: 510
Is it possible to append the same value to two different arrays in one statement? For e.g.,
a = [], b = []
a,b << 10
Upvotes: 4
Views: 153
Reputation: 110675
a = [1,2]; b = [3]
a,b = [a, b].product([10]).map(&:flatten)
or
a,b = [a,b].zip(Array.new(2,10)).map(&:flatten)
or
a,b = [a,b].zip([10]*2).map(&:flatten)
# => a = [1, 2, 10]
, b = [3, 10]
This obviously generalizes to any number of arrays.
Upvotes: 1
Reputation: 118271
How is this using initialize_copy
:
a=[]
b=[]
a.object_id # => 11512248
b.object_id # => 11512068
b.send(:initialize_copy,a << 10)
a # => [10]
b # => [10]
a.object_id # => 11512248
b.object_id # => 11512068
Upvotes: 1
Reputation: 29493
If you want to keep different arrays then I think the only possibility is to do this:
a, b = a << 10, b << 10
Obviously, it does not fulfill the requirement to write the value just once. With the comma it is possible to write values in an array notation. On the left side of the assignment are two values which can consume an array up to length two.
What is on the right side of the assignment? There are two values written in array notation. After evaluation you could write:
a, b = [[a], [b]]
# a <- [a]
# b <- [b]
Alternatively, if you are fine with semicolon:
a << 10; b << 10;
Upvotes: 5
Reputation: 1212
You can do like this
a = b << 10
p a.inspect
p b.inspect
Hope it resolve your issue
Upvotes: -2