Delete an array element if the index position is greater than a certain value

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

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

I looked at drop, delete_ifetc. I tried to accomplish this using the each_with_indexfollowing:

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

How can I remove an array element if its array position is greater than a certain value?

+4
source share
5 answers

Here are a few other ways to return asans elements to> = indexes index, which are probably better expressed as "returning the first elements index". All below come back ["a", "b"]).

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

(.. a )

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

(a "" )

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 
+6

slice! . , !, .

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

a = [1, 2]

+4

Array#first n .

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

, :

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

with_index:

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

:

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"]
+1

: " , ?".

, , , , .

:

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

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

All Articles