Add the same value to two or more arrays

Is it possible to add one value to two different arrays in one expression? For instance,

a = [], b = [] 
a,b << 10 
+4
source share
6 answers
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 is obviously generalized to any number of arrays.

+1
source

If you want to keep different arrays, I think the only way is to do this:

a, b = a << 10, b << 10

Obviously, this does not meet the requirement to write a value only once. With a comma, you can write values ​​in array notation. On the left side of the task are two values ​​that can consume an array of up to two.

? . :

a, b = [[a], [b]]

# a <- [a]
# b <- [b]

, :

a << 10; b << 10;
+5

:

[a,b].each { |arr| arr.push( 10 ) }
+4

How is it used : 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
+1
source

Sure.

a,b = [],[]
c = 10

a,b = a.push(c),b.push(c)
0
source

You can do it as follows:

a = b << 10
p a.inspect
p b.inspect

Hope it solves your problem.

-2
source

All Articles