Marco Song Marco Song - 29 days ago 24
Ruby Question

Ruby can not remove elements in array

For the piece of code below.

I want to remove element which is equals to 3 from an array.
But the code only removed the first element. When I debug the code,

I found that the iterator only loops though the array one time instead of two.

I am not sure what causes the problem. Any help will be appreciated.

nums = [3,3]
def remove_element(nums, val)
nums.each_with_index do |num,index|
if num == val
nums.slice!(index)
end
end
nums.length
end

remove_element(nums,3)

Answer

As rightly commented, you have modified the array while iterating it, due to which it removed the first element, and concluded the iteration. If you put a print statment inside nums.each_with_index loop, you will see it gets printed only once.

A better way to remove an element can be using reject method like following:

nums.reject!{|item| item == 3}