There are two methods below; both are the same except one clone
s the input whereas the other does not.
Method 1
arr = [1,2,3,1,2,3]
def remove_smallest(array)
new = array
new.reject! {|i| i <= new.min}
new
end
remove_smallest(arr)
#=> [2,3,2,3]
arr
#=> [2,3,2,3]
Method 2
arr = [1,2,3,1,2,3]
def remove_smallest(array)
new = array.clone
new.reject! {|i| i <= new.min}
new
end
remove_smallest(arr)
#=> [2,3,2,3]
arr
#=> [1,2,3,1,2,3]
Without the clone
, the method will mutate the original input even if I perform all operations on a copy of the original array.
Why is an explicit clone
method needed to avoid this mutation?