ruby - 枚举器的未定义方法排序

标签 ruby sorting methods iterator

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

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

当我尝试运行代码时:

x = Greedy.new("cents", 130, 50, 25, 10, 5)

我得到一个错误:

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>'

作为 Ruby 的新手,我不知道这意味着什么,也不知道如何修复它,因为 [50, 25, 10, 5].sort! 是一个完全有效的方法。 . 如何修复此错误?

最佳答案

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

如果您在没有 block 的情况下调用 map,它将返回一个 Enumerator。你想在这里映射什么?如果您不想对 coins 的值做任何事情,只需分配 @currency = coins.sort.reverse 并保存您自己的 sort!反向步骤。

关于ruby - 枚举器的未定义方法排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10414955/

相关文章:

Java Set 保留顺序?

javascript - javascript中的Date.UTC()方法是否创建本地时区或GMT

java - 如何在方法中添加静态变量号?

ruby-on-rails - Ruby:合并数组或散列

ruby-on-rails - 将类动态解析为全局范围

ruby-on-rails - 从字符串中删除引号,以便我可以将其添加到 Controller 操作中

c - 基数排序算法对于不同顺序的数据可能有不同的运行时间?

ruby-on-rails - Ruby 上周日的年月日

ruby - 垂直排序游戏列表

javascript - var 与 function,哪个更适合常量和方法