Undefined sorting method for an enumerator

I implemented the Greedy algorithm in ruby ​​using the following code:

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

When I try to run the code:

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

I get an error message:

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

Being very new to Ruby, I have no idea what this means and how to fix it, because it [50, 25, 10, 5].sort!is an absolutely correct method ... How to fix this error?

+3
source share
2 answers

Your problem is here: @currency = coins.map

If you call mapwithout a block, it will return Enumerator. What did you want on the map? If you do not want to do anything with the values coins, just assign @currency = coins.sort.reverseand save the steps sort!and themselves reverse.

+8
source

. . .

* splatten, . , ,

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

:

@currency = coins.to_a.sort

to_a :

coins = coins.map{|x| x}
+1

All Articles