Move an element to an array to another array

Suppose we have arrays x = ['a', 'b', 'c'] and y . Is there an easy way to move, say, the second element of x , to y ? So, at the end of << 22> ['a', 'c'] and y is ['b'] .

+4
source share
4 answers

yep, it will look like this:

 y.push x.delete_at(1) 

delete_at will remove the element with the given index from the array it called on, and return this object

+4
source

Special code for this example. Perhaps this will not work on your other arrays. Instead of actually moving the element, let's split the old array and build two new arrays.

 x = ['a', 'b', 'c'] x, y = x.partition {|i| i != 'b'} x # => ["a", "c"] y # => ["b"] 

The delete_at approach is probably better for your situation, but you know it's good to know the alternatives :)

+8
source

Yes. For a specific item:

 y = [] y << x.delete('b') 

For a specific index:

 y = [] y << x.delete_at(1) 

This material is well documented , by the way.

+4
source
 x = ['a', 'b', 'c'] y = [] 

Index removal:

 y << x.delete_at(1) 

Delete by object:

 y << x.delete('b') 
+2
source

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


All Articles