Ruby - Array Array Sorting

Introduction

The sort method compares adjacent array elements using the comparison operator <=>.

This operator is defined for many Ruby classes, including Array, String, Float, Date, and Fixnum.

You can define your own sorting routine by sending a block to the sort method.

The following block determines the comparison used by the sort method:

Demo

arr=['h','e','l','l','o',' ','w','o','r','l','d'] 

arr.sort{ # from   ww w  . j  a  v a  2 s . c  o  m
  |a,b| 
    a.to_s <=> b.to_s 
}

Here arr is an array object, and the variables a and b represent two contiguous array elements.

Demo

arr = ['h','e','l','l','o',' ',nil,'w','o','r','l','d',1,2,3,nil,4,5] 
# sort ascending from nil upwards 
sorted_arr = arr.sort{ #   www . ja va2 s.c  o m
    |a,b| 
        a.to_s <=> b.to_s 
    } 

p(sorted_arr )

Result

To sort array in descending order: change the order of the items on either side of the comparison operator:

Demo

arr = ['h','e','l','l','o',' ',nil,'w','o','r','l','d',1,2,3,nil,4,5] 

reverse_sorted_arr = arr.sort{ # w  w w. ja  va 2 s. c  om
    |a,b| 
        b.to_s <=> a.to_s 
    } 

p(reverse_sorted_arr )

Result

Related Topics