Is there ruby ​​oneliner to concatenate nested arrays without temporary copies?

a = [ 'a' ]
b = [ 'b' ]

def c

    return [ 'c' ], [ 'd' ]

end

a, b += c # -> would be awesome, but gives syntax error

a, b = a + c.first, b + c.last # clunky and will call method twice...

# desired result
#
a == [ 'a', 'c' ]
b == [ 'b', 'd' ]

Right now, I often find myself writing:

t, tt = c
a += t
b += tt

but kind of ugly if you ask me.

Edit : single element arrays seem to have confused some people, as the few answers below just don't answer the question. I made this clearer by letting each array have at least 2 elements.

Edit2 : I submitted a function request with a ruby ​​kernel to implement complex assignments on destructed arrays.

+4
source share
4 answers
a,b = [a+b,c].transpose
  #=> [["a", "c"], ["b", "d"]] 
a #=> ["a", "c"] 
b #=> ["b", "d"] 
+5
source
a, b = (a+b).zip(c)
# a => ["a", "c"]
# b => ["b", "d"]

Hope this helps.

+5

" ", inplace

a1 = [ 'a1' ]
a2 = [ 'a2' ]
a3 = [ 'a3' ]
aa = [ a1, a2, a3 ]
cc = [ 'c1', 'c2', 'c3' ]

aa.each_with_object(cc.each) { |e, memo| e << memo.next }
#⇒ #<Enumerator: ["c1", "c2", "c3"]:each> # do not care, it’s memo

[a1, a2, a3]
#⇒ [ ["a1", "c1"], ["a2", "c2"], ["a3", "c3"] ]

Whether ccfor some reason the array is an array of arrays, as indicated in the question, it should be smoothed out at some step, depending on how it should be added to the arrays a.

+3
source

None of the answers work yet, so for now I came up with nest_concat! (deep_concat seemed wrong because we want only one deep):

class Array

    def nest_concat! other

        each_with_index { |arr, i| self[i].concat other[ i ] }

    end

    def nest_concat other

        d = map( &:dup )
        each_with_index { |arr, i| d[i].concat other[ i ] }

        d

    end

end

Allows you to write:

a = [ 'a', 'b' ]
b = [ 'c', 'd' ]

def c

    return [ 'A', 'B' ], [ 'C', 'D' ]

end

[ a, b ].nest_concat! c
p a
p b

gives

["a", "b", "A", "B"]
["c", "d", "C", "D"]
0
source

Source: https://habr.com/ru/post/1648194/


All Articles