Sorting
If you look up ruby documentation, you'll find a few different sorting methods at your disposal for Enumerable
objects (like Array
), primarily sort
and sort_by
and their variations.
Both sort
and sort_by
return a new sorted Array
without modifying the original.
Enumerable#sort
Pass in a block telling it how to compare two objects.
unsorted = 5.times.map { rand(100) }
new_sorted_array = unsorted.sort { |x, y| x <=> y }
new_sorted_array = unsorted.sort # this is equivalent because we're only using the default comparator, <=>
puts "still unsorted: #{unsorted.inspect}"
puts "sorted: #{new_sorted_array.inspect}"
Enumerable#sort_by
Pass in a block that retrieves the key by which the objects should be sorted (using the default comparator, <=>
, i think)
unsorted_wrapped_numbers = 5.times.map { [rand(100)] }
new_sorted_array = unsorted_wrapped_numbers.sort_by { |wrapped_number| wrapped_number.first }
puts "still unsorted: #{unsorted_arrays_of_single_numbers.inspect}"
puts "sorted: #{new_sorted_array.inspect}"
Note that this information is all available online, and I've linked each section above to its relevant ruby documentation. I often refer to them, myself.
Comparing "alphabetically"
By default, integers are comparable with integers and strings with strings, using the default comparator, <=>
:
94 <=> 2 # returns 1, meaning "greater than"
3 <=> 3 # returns 0, meaning "equal"
"goodbye" <=> "hello" # returns -1, meaning "less than", since "g" comes before "h", alphabetically
You'll need to define how an integer is going to be compared to a string, though:
5 <=> "word" # returns nil
Consider converting the number into a string, for example:
5.to_s <=> "word"