简体   繁体   English

红宝石排序哈希按字母顺序排列

[英]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 我有一个哈希数组,我想基于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? 有什么办法吗?

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

See Enumerable#sort_by 参见Enumerable#sort_by

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). sort_by是在此处使用的自然方法,但我很好奇它与将键:name的值排序然后使用values_at以正确顺序提取哈希值的方法(需要先转换数组)进行比较散列)。

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. 看起来性能几乎是相同的,因此更简单,读取效果更好的sort_by似乎是这里的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM