As @steenslag has pointed out, the delete method will do what you want:
n = [1,2,3,3,4,5,6,3,4,5,3,2,1,8]
n.delete(3)
n
returns: [1, 2, 4, 5, 6, 4, 5, 2, 1, 8]
It's worth looking at this alternative to your code:
nums = [3,3]
def remove_element(nums, val)
nums.each_with_index do |num,index|
nums_before_slice = nums.clone
if num == val
sliced = nums.slice!(index)
end
puts "nums: #{nums_before_slice}, index: #{index}, sliced: #{sliced.inspect}"
end
end
remove_element(nums,3)
puts "Result: #{nums.inspect}"
The output will be:
nums: [3, 3], index: 0, sliced: 3
Result: [3]
As you can see, the iteration only happens once, because the second element has been removed before it is time to do the second iteration.
Compare that result to this version of the code:
nums = [3,3]
def remove_element(nums, val)
nums.clone.each_with_index do |num,index|
nums_before_slice = nums.clone
if num == val
sliced = nums.slice!(index)
end
puts "nums: #{nums_before_slice}, index: #{index}, sliced: #{sliced.inspect}"
end
end
remove_element(nums,3)
puts "Result: #{nums.inspect}"
Which results in:
nums: [3, 3], index: 0, sliced: 3
nums: [3], index: 1, sliced: nil
Result: [3]
This now runs the iteration over a copy of the original nums, but the result is the same, as on the second iteration - there is no second element to be removed.