0

I have a method that prints out my cards below. I want to create a method that will print out the cards in descending order. I would have to create a new method. I've tried a few things but here I am.

    def print_cards    
      cards.all.each.with_index(1) do |card, index|
        puts "#{index}. #{card.name}"
      end 
    end 

  • Can you show what `cards` looks like and a concrete example of the actual and expected results? Thanks. – ggorlen Nov 10 '19 at 04:19

1 Answers1

1

You should use the sort_by method of Ruby's Enumerable module.

The basic idea is you provide a block that maps each value in the enumeration into a numerical value that can be used to sort the collection.

For example if you have a collection of Strings and you want to sort them by length you can use something like this where each item in the collection is mapped to its size/length. The first example sorts the array in ascending order while the second sorts in descending order.

my_array = ["a", "aa", "aaaa", "aaa"]

puts my_array.sort_by { |item| item.size }
puts my_array.sort_by { |item| -item.size }
nPn
  • 16,254
  • 9
  • 35
  • 58
  • Damn, that's clean as hell. I've always done the full |a, b| a <=> b, and swapping to b <=> a for a reverse sort. But that way you did it is actually so much cleaner – TedTran2019 Nov 10 '19 at 07:03