4

I am trying to delete elements from an array if its index is greater than a certain value. I am looking to do something like this:

a = ["a", "b", "c"]
b = a.delete_if {|x| x.index > 1 }

I took a look at drop, delete_if, etc. I tried completing this using each_with_index like this:

new_arr = []
a.each_with_index do |obj, index|
    if index > 1
        obj.delete
    end
    new_arry << obj
end

How can I delete an array element if it's array position is greater than a certain value?

5 Answers 5

7

Here are some other ways to return a sans elements at indices >= index, which is probably better expressed as "returning the first index elements". All below return ["a", "b"]).

a = ["a", "b", "c", "d", "e"]
index = 2

Non-destructive (i.e., a is not altered)

a[0,index]
index.times.map { |i| a[i] }

Destructive (a is modified or "mutated")

a.object_id #=> 70109376954280 
a = a[0,index]
a.object_id #=> 70109377839640

a.object_id #=> 70109377699700 
a.replace(a.first(index))
a.object_id #=> 70109377699700 
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I needed. Thank you for the detailed answer.
4

You can use slice! and give it a range. It is a destructive method as indicated by the !, so it will mutate your array.

a = [1, 2, 3, 4]
a.slice!(2..-1)

a = [1, 2]

Comments

3

Array#first gives you the first n elements.

b = a.first(1)
# => ["a"]

If you want to do it in a destructive way, then this will do:

a.pop(a.length - 1)
a # => ["a"]

2 Comments

Lets say I had an array that was 20 elements long and wanted to delete index positions 9 and up? That's more specific to what I am trying to do
I'm sure @sawa meant n where he wrote 1. (s: n needs backticks.)
2

You can append with_index:

a = ["a", "b", "c"]
a.delete_if.with_index { |x, i| i > 1 }
a #=> ["a", "b"]

Another example:

a = ("a".."z").to_a
a.delete_if.with_index { |x, i| i.odd? }
#=> ["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"]

Comments

0

Going by your question, "How can I delete an array element if it's array position is greater than a certain value?".

I assume what you want is that the final array you have should contain only elements before the specified index.

You can just do this:

your_array.select { |element| your_array.index(element) < max_index }

E.g

figures = [1,2,3,4,5,6]
figures.select{ |fig| figures.index(fig) < 3 }
# => [1, 2, 3]

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.