Ankush Ganatra
Ankush Ganatra

Reputation: 510

Append the same value to two or more arrays

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

Answers (6)

Cary Swoveland
Cary Swoveland

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

Arup Rakshit
Arup Rakshit

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

Konrad Reiche
Konrad Reiche

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

Neil Slater
Neil Slater

Reputation: 27207

I would do this:

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

Upvotes: 4

geekdev
geekdev

Reputation: 1212

You can do like this

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

Hope it resolve your issue

Upvotes: -2

Oto Brglez
Oto Brglez

Reputation: 4193

Sure.

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

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

Upvotes: 0

Related Questions