Reputation: 605
I am trying to delete all elements from an array. For example:
@array = [1,2,3,4,5]
@array.each do |element|
@array.delete(element)
end
Now, I understand why the code above does not work. However, I am tasked with deleting all elements of an array while using this delete_entry
method:
def delete_entry(entry)
@array.delete(entry)
end
I have read that removing elements in the midst of iteration is disallowed by design in ruby. Any ideas as to how I would go about deleting all elements from an array while using the delete_entry
method in my implementation?
Upvotes: 0
Views: 1985
Reputation: 110675
def delete_entry(entry)
@array.delete(entry)
end
@array = [1,2,3,4,5]
delete_entry(@array.first) until @array.empty?
@array #=> []
I think this reads better than using an enumerator and requires fewer operations when @array
contains duplicate values.
Upvotes: 3
Reputation: 80065
Loop through the array in reverse:
@array = [1,2,3,4,5]
@array.reverse_each do |element|
@array.delete(element)
end
p @array # => []
Upvotes: 2
Reputation: 48599
class Dog
attr_reader :array
def initialize
@array = [1, 2, 3]
end
def delete_entry(entry)
@array.delete(entry)
end
end
d = Dog.new
d.array.length.times do
d.delete_entry(d.array[0])
end
p d.array
--output:--
[]
I have read that removing elements in the midst of iteration is disallowed by design in ruby.
Ridiculous. It just won't work as you may expect. Here's why:
deleting elements from an array while iterating over the array
Upvotes: 1
Reputation: 4077
@array = [1,2,3,4,5]
@_array = @array.clone
@_array.each do |element|
delete_entry(element)
end
Upvotes: 1