将Ruby哈希拆分为已排序的键/关联值

时间:2022-11-25 21:17:13

Let's say I have a hash in Ruby like this:

假设我在Ruby中有一个哈希,就像这样:

d = {1 => 'one', 3 => 'three', 2 =>'two'}

and I wish to get

我希望得到

x = [1, 2, 3]
y = ['one', 'two', 'three']

that is, I want the sorted keys in x, and the corresponding values in y. I potentially want to use a custom sort order for x.

也就是说,我希望x中的排序键和y中的相应值。我可能想要使用x的自定义排序顺序。

What's the cleanest, simplest way to do this?

什么是最干净,最简单的方法?

3 个解决方案

#1


8  

Easy:

简单:

x,y = d.sort.transpose

Or, with a custom sort:

或者,使用自定义排序:

x,y = d.sort_by {|k,v| whatever}.transpose

#2


8  

my original answer

我的原始答案

x = d.keys.sort
y = x.map {|k| d[k]}

but you should also see glenn mcdonald's answer

但你也应该看到格伦麦克唐纳的回答

x,y = d.sort.transpose

#3


0  

x, y = d.keys.sort{|a,b| a <=> b}.inject([]){|result, key| result << [key, d[key]]}.transpose

... made the sort explicit so you can change it to whatever you like.

...明确排序,以便您可以将其更改为您喜欢的任何内容。

#1


8  

Easy:

简单:

x,y = d.sort.transpose

Or, with a custom sort:

或者,使用自定义排序:

x,y = d.sort_by {|k,v| whatever}.transpose

#2


8  

my original answer

我的原始答案

x = d.keys.sort
y = x.map {|k| d[k]}

but you should also see glenn mcdonald's answer

但你也应该看到格伦麦克唐纳的回答

x,y = d.sort.transpose

#3


0  

x, y = d.keys.sort{|a,b| a <=> b}.inject([]){|result, key| result << [key, d[key]]}.transpose

... made the sort explicit so you can change it to whatever you like.

...明确排序,以便您可以将其更改为您喜欢的任何内容。