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']
.
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With