Sorting Hashes 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.
Explanation of sorting using hashing if the array has negative and positive numbers: Step 1: Create two hash arrays, one for positive and the other for negative. Step 2: the positive hash array will have a size of max and the negative array will have a size of min.
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.
Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.
Simples:
array_of_hashes.sort_by { |hsh| hsh[:zip] }
Note:
When using sort_by
you need to assign the result to a new variable: array_of_hashes = array_of_hashes.sort_by{}
otherwise you can use the "bang" method to modify in place: array_of_hashes.sort_by!{}
sorted = dataarray.sort {|a,b| a[:zip] <=> b[:zip]}
Use the bang to modify in place the array:
array_of_hashes.sort_by!(&:zip)
Or re-assign it:
array_of_hashes = array_of_hashes.sort_by(&:zip)
Note that sort_by method will sort by ascending order.
If you need to sort with descending order you could do something like this:
array_of_hashes.sort_by!(&:zip).reverse!
or
array_of_hashes = array_of_hashes.sort_by(&:zip).reverse
If you want to paginate for data in array you should require 'will_paginate/array' in your controller
If you have Nested Hash (Hash inside a hash format) as Array elements (a structure like the following) and want to sort it by key (date here)
data = [
{
"2018-11-13": {
"avg_score": 4,
"avg_duration": 29.24
}
},
{
"2017-03-13": {
"avg_score": 4,
"avg_duration": 40.24
}
},
{
"2018-03-13": {
"avg_score": 4,
"avg_duration": 39.24
}
}
]
Use Array 'sort_by' method as
data.sort_by { |element| element.keys.first }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With