sort array of hashes ruby
To sort an array of hashes in Ruby, you can use the sort_by
method. Here are the steps to achieve this:
Start by defining your array of hashes. For example,
array = [{name: "John", age: 30}, {name: "Alice", age: 25}, {name: "Bob", age: 35}]
.Use the
sort_by
method to sort the array based on a specific key in the hashes. For example, if you want to sort the array by thename
key, you can doarray.sort_by { |hash| hash[:name] }
.If you want to sort the array in descending order, you can use the
reverse
method after thesort_by
method. For example,array.sort_by { |hash| hash[:name] }.reverse
.If you want to sort the array based on multiple keys, you can specify multiple criteria in the
sort_by
block. For example,array.sort_by { |hash| [hash[:name], hash[:age]] }
will first sort the array byname
and then byage
.
That's it! Following these steps will allow you to sort an array of hashes in Ruby.