tags:

views:

160

answers:

3

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

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.

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

+8  A: 

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
jrhicks
A: 
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.

wombleton
+6  A: 

Easy:

x,y = d.sort.transpose

Or, with a custom sort:

x,y = d.sort_by {|k,v| whatever}.transpose
glenn mcdonald
You've got my vote.
jrhicks
ok! this is obviously the 'correct' way. thanks.
Peter
transpose = unzip ... odd naming choice but has my vote as well
Sam Saffron