sort items in array by desc in Ruby
Code snippet on how to sort items in array by desc in Ruby
arr = [5, 2, 4, 1, 3]
arr.sort { |a,b| b <=> a }
This code is sorting an array using Ruby. The array provided is arr = [5, 2, 4, 1, 3]. The ‘sort’ method is then used to sort the array in descending order. This is done by using the comparison operator (‘<=>’) to compare two items in the array, ‘a’ and ‘b’. If the comparison operator evaluates to 1 then ‘a’ is greater than ‘b’, whereas a -1 means ‘b’ is greater than ‘a’. In this code, the comparison operator is used to order the array in descending order, meaning that ‘b’ is placed before ‘a’ in the ordered array. After the code is run, the array will be ordered in descending order as [5, 4, 3, 2, 1].