1

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?

2 Answers 2

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

See Enumerable#sort_by

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.