Home > database >  How do I remove the first array inside of a nested array with ruby on rails?
How do I remove the first array inside of a nested array with ruby on rails?

Time:03-18

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

CodePudding user response:

you can try the following method

array.drop(1)

CodePudding user response:

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

  • Related