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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With