I have the following code:
Array.class_eval do
def abs_sort
new_array = self
self.each do |x|
new_array.push(x.abs)
end
return new_array.sort
end
end
When I try to run the code:
[1, 4, -2].abs_sort
Nothing happens, it just shows a blank screen. Why?
You need to set
new_arrayto an actual new array, notself:What’s happening is that since
new_arrayisself, you’re adding items to the end of the array as you iterate over it, which means that the iteration never ends since you always have more items, and your method infinitely loops.