ruby sort_by 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14113909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby sort_by method
提问by U-L
I have just started to learn ruby. I have an array of hashes. I want to be able to sort the array based on an elementin the hash. I think I should be able to use the sort_by method. Can somebody please help?
我刚刚开始学习ruby。我有一个哈希数组。我希望能够根据哈希中的元素对数组进行排序。我想我应该能够使用 sort_by 方法。有人可以帮忙吗?
#array of hashes
array = []
hash1 = {:name => "john", :age => 23}
hash2 = {:name => "tom", :age => 45}
hash3 = {:name => "adam", :age => 3}
array.push(hash1, hash2, hash3)
puts(array)
Here is my sort_by code:
这是我的 sort_by 代码:
# sort by name
array.sort_by do |item|
item[:name]
end
puts(array)
Nothing happens to the array. There is no error either.
数组没有任何反应。也没有错误。
回答by steenslag
You have to store the result:
您必须存储结果:
res = array.sort_by do |item|
item[:name]
end
puts res
Or modify the array itself:
或者修改数组本身:
array.sort_by! do |item| #note the exclamation mark
item[:name]
end
puts array
回答by Saravanan Kothandapani
You can use sort by method in one line :
您可以在一行中使用 sort by 方法:
array.sort_by!{|item| item[:name]}
回答by ray
You can do it by normal sortmethod also
您也可以通过正常的排序方法来完成
array.sort { |a,b| a[:name] <=> b[:name] }
Above is for ascending order, for descending one replace a with b. And to modify array itself, use sort!
上面是升序,降序是用b替换a。并修改数组本身,使用排序!

