Enumerator的未定义方法排序

Bob*_*les 3 ruby sorting methods iterator

我使用以下代码在ruby中实现了Greedy算法:

class Greedy
  def initialize(unit, total, *coins)
    @total_coins1 = 0
    @total_coins2 = 0
    @unit = unit
    @total = total
    @reset_total = total
    @currency = coins.map 
    @currency.sort!
    @currency = @currency.reverse
    unless @currency.include?(1)
      @currency.push(1)
    end
  end
  def sorter
    @currency.each do |x|
      @pos = @total / x
      @pos = @pos.floor
      @total_coins1 += @pos
      @total -= x * @pos
      puts "#{@pos}: #{x} #{@unit}"
    end
    puts "#{@total_coins1} total coins"
  end
end
Run Code Online (Sandbox Code Playgroud)

当我尝试运行代码时:

x = Greedy.new("cents", 130, 50, 25, 10, 5)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

NoMethodError: undefined method `sort!' for #<Enumerator: [50, 25, 10, 5]:map>
    from /Users/Solomon/Desktop/Ruby/greedy.rb:9:in `initialize'
    from (irb):2:in `new'
    from (irb):2
    from /Users/Solomon/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
Run Code Online (Sandbox Code Playgroud)

作为Ruby的新手,我不知道这意味着什么,也不知道如何解决它,因为这[50, 25, 10, 5].sort!是一个非常有效的方法......我该如何解决这个错误?

Mic*_*ohl 8

你的问题在这里: @currency = coins.map

如果你打电话map没有阻止,它将返回一个Enumerator.你想在这里映射什么?如果有什么你想要做的价值coins,只是分配@currency = coins.sort.reverse和保存自己sort!reverse步骤.