danynl
danynl

Reputation: 299

ruby sort hashes within array in alphabetical order

I have an array of hashes and I want to sort the hashes in alphabetical order based on the value of the key :name

names_array = [{:name=>"item3",:ID=>"345"},{:name=>"item1",:ID=>"127"},{:name=>"item2",:ID=>"298"}]

the output should look like:

names_array = [{:name=>"item1",:ID=>"127"},{:name=>"item2",:ID=>"298"},{:name=>"item3",:ID=>"345"}]

Is there any way to this?

Upvotes: 1

Views: 1520

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

sort_by is the natural method to use here, but I was curious how it would compare with a method that sorted the values of the key :name and then used values_at to extract the hashes in the correct order (which requires that the array be first converted to a hash).

def sort_by_method(names_array)
  names_array.sort_by { |hash| hash[:name] }
end

def values_at_method(names_array)
  h = names_array.each_with_object({}) { |g,h| h[g[:name]] = g }
  h.values_at *h.keys.sort
end

require 'fruity'

ALPHA = ('a'..'z').to_a

def bench_em(size, name_size)
  names_array = size.times.map { { a: 1, name: ALPHA.sample(name_size).join, c: 2 } }
  compare do 
    _sort_by   { sort_by_method names_array }
    _values_at { values_at_method names_array }
  end
end

bench_em(100,     10)
Running each test 64 times. Test will take about 1 second.
_sort_by is similar to _values_at

bench_em(1_000,   10)
Running each test 4 times. Test will take about 1 second.
_values_at is similar to _sort_by

bench_em(10_000,  10)
Running each test once. Test will take about 1 second.
_sort_by is similar to _values_at

bench_em(100_000, 10)
Running each test once. Test will take about 8 seconds.
_sort_by is similar to _values_at

It appears performance is about the same, so sort_by, which is simpler and reads better, appears to be the best choice here.

Upvotes: 1

Sagar Pandya
Sagar Pandya

Reputation: 9508

names_array.sort_by { |hash| hash[:name] }
#=> [{:name=>"item1", :ID=>"127"}, {:name=>"item2", :ID=>"298"}, {:name=>"item3", :ID=>"345"}]

See Enumerable#sort_by

Upvotes: 3

Related Questions