4

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'].

4 Answers 4

9

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 :)

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

4

Yes. For a specific element:

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

For a specific index:

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

This kind of stuff is well documented, btw.

Comments

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

To delete by index:

y << x.delete_at(1)

To delete by object:

y << x.delete('b')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.