Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete array element if index position is greater than a specific value

Tags:

arrays

ruby

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?

like image 832
Jbur43 Avatar asked Dec 04 '22 01:12

Jbur43


1 Answers

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 
like image 151
Cary Swoveland Avatar answered May 22 '23 12:05

Cary Swoveland