Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move item in array to another array

Tags:

ruby

Let's suppose that 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 that in the end, x is ['a', 'c'] and y is ['b'].

like image 463
Jean-Luc Avatar asked Nov 30 '22 22:11

Jean-Luc


2 Answers

A special code for this example. It might not work on your other arrays. Instead of actually moving element, let's take the old array apart and construct two new arrays.

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

x, y = x.partition {|i| i != 'b'}

x # => ["a", "c"]
y # => ["b"]

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

like image 80
Sergio Tulentsev Avatar answered Dec 07 '22 22:12

Sergio Tulentsev


yep, it would look like this:

y.push x.delete_at(1)

delete_at will delete an element with given index from an array it's called on and return that object

like image 38
Vlad Khomich Avatar answered Dec 07 '22 22:12

Vlad Khomich