Search code examples
rubyenumerable

NoMemoryError in Array#max


I'm working on a codewars problem to parse an integer and re-order its digits in descending order. My working solution is below; I decided to use string methods to quickly parse the digits (instead of mods or log_10s):

# descending_order : int => int
# Takes an int, re-orders its digits in descending order, and returns that

# ex. descending_order(1234) => 4321

def descending_order(n)
  n.to_s.chars.sort.reverse.join.to_i
end

However, when playing around with the solution, I also tried the following variation, which threw a NoMemoryError for a reasonably small input:

def descending_order(n)
  n.to_s.chars.max(n).join.to_i
end

yields:

descending_order(456454576895645)
NoMemoryError: failed to allocate memory
from (pry):129:in `max'

Clearly, sort is the proper way to sort an array over max(<array_length>), but I'm curious about why max is hogging so much memory here. What leads to this behavior, and do I need to be careful with similar situations (e.g. taking max(20) off an array of 100 integers)?


Solution

  • As documented here, if n is given then maximum n elements is returned, essentially allocating array of size n as well, which is the cause of your NoMemoryError.