【问题标题】:Undefined method sort for Enumerator枚举器的未定义方法排序
【发布时间】:2012-05-02 13:39:29
【问题描述】:

我使用以下代码在 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! 是一个完全有效的方法......我该如何修复这个错误?

【问题讨论】:

    标签: ruby sorting methods iterator


    【解决方案1】:

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

    如果您在没有块的情况下调用map,它将返回一个Enumerator。你想在这里映射什么?如果您不想处理 coins 的值,只需分配 @currency = coins.sort.reverse 并为自己节省 sort!reverse 步骤。

    【讨论】:

    • 我想将coins 映射到一个数组
    • 查看更新。顺便说一句,您不必将其映射到数组,因为您在参数列表中使用了 splat 运算符 (*),它已经是一个数组。
    • 这不是我真正想要的,抱歉,我需要对@currency 进行排序,但那不行。
    • 当然@currency如果你这样做会被排序。你取coins数组,在上面调用sort,然后reverse它(顺便说一下,有更好的方法进行反向排序,见sort_by,然后将最终结果分配给@currency
    【解决方案2】:

    枚举器没有排序方法。它属于 Enumerable。不带block的map方法返回一个枚举器。

    在您的示例中,您已经使用了 * splatten 运算符,因此硬币已经是一个数组。但是如果你坚持强制转换它,你可以使用

    @currency  = coins.to_a
    @currency = @currency.sort!
    

    或者直接缩短为:

    @currency = coins.to_a.sort
    

    to_a 方法会将其转换为数组,相当于:

    coins = coins.map{|x| x}
    

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多