0

let's say I have a nested array like so

array = [[1,2,3], [4,5,6], [7,8,9]]

How would I remove the very first array in the nested array so it could end up like so

array = [[4,5,6],[7,8,9]]
2
  • Do you need to first detect if it is an array or not, or is it always an array? Commented Mar 18, 2022 at 2:07
  • while mechnicov and Cary Swoveland point out many possible solutions, I think Farhad Ajaz's solution is the most strait forward. That being said, a simple google search of "ruby remove first element from array" would yield many solutions, including those found on this site, which might result in a the question being marked as a duplicate Commented Mar 18, 2022 at 3:59

2 Answers 2

3

you can try the following method

array.drop(1)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that drop doesn't modify array. (as requested by the OP)
3

There are many-many ways to do it

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can mutate array in place with such methods

# Array#delete_at

array.delete_at(0)
array # => [[4, 5, 6], [7, 8, 9]]
# Array#slice!

array.slice!(0)
array # => [[4, 5, 6], [7, 8, 9]]
# Array#shift

array.shift # or array.shift(1)
array # => [[4, 5, 6], [7, 8, 9]]

or you can assign new value

# Array#drop

array = array.drop(1)
# Array#[]

array = array[1..]

or replace content to save link to object

# Array#replace

array.replace(array[1..-1]) # new array as argument of replace

or more difficult ways

# Array#reject

array = array.reject!.with_index { |_, index| index.zero? }
# Array#reject!

array.reject!.with_index { |_, index| index.zero? }
# Array#select

array = array.select.with_index { |_, index| index.positive? }
# Array#select!

array.select!.with_index { |_, index| index.positive? }

I'm sure there are many other methods

Please look in the docs to explore it:

https://ruby-doc.org/core/Array.html

1 Comment

Two more: array.replace(array[1..-1]) (mutating) and _,*a = array, a being the new array (non-mutating).

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.