Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort strings and numbers in Ruby

Tags:

sorting

ruby

I want to sort an array by strings first and then numbers. How do I do this?

like image 493
thenengah Avatar asked Dec 23 '09 22:12

thenengah


People also ask

How do you sort an array of numbers in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)

How do you sort objects in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

What is sort in Ruby?

Ruby | Enumerable sort() function The sort() of enumerable is an inbuilt method in Ruby returns an array which contains the enum items in a sorted order. The comparisons are done using operator or the optional block.

How do you sort hash in Ruby?

To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.


2 Answers

A general trick for solving tricky sorts is to use #sort_by, with the block returning an array having the primary and secondary sort order (and, if you need it, tertiary, etc.)

a = ['foo', 'bar', '1', '2', '10']  
b = a.sort_by do |s|
  if s =~ /^\d+$/
    [2, $&.to_i]
  else
    [1, s]
  end
end
p b    # => ["bar", "foo", "1", "2", "10"]

This works because of the way array comparison is defined by Ruby. The comparison is defined by the Array#<=> method:

Arrays are compared in an “element-wise” manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (i.e. the two corresponding elements are not equal), that result is returned for the whole array comparison.

like image 54
Wayne Conrad Avatar answered Oct 07 '22 19:10

Wayne Conrad


Sort an array of mixed numbers and strings by putting the numbers first, and in order, followed by the strings second, and in order.

>> a = [1, 2, "b", "a"]

>> a.partition{|x| x.is_a? String}.map(&:sort).flatten
=> ["a", "b", 1, 2]
like image 44
Peter Avatar answered Oct 07 '22 17:10

Peter