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 

1
  • Can you show what cards looks like and a concrete example of the actual and expected results? Thanks. Commented Nov 10, 2019 at 4:19

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.