Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Ruby hash into sorted keys / associated values

Tags:

ruby

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?

like image 504
Peter Avatar asked Dec 06 '22 04:12

Peter


2 Answers

Easy:

x,y = d.sort.transpose

Or, with a custom sort:

x,y = d.sort_by {|k,v| whatever}.transpose
like image 146
glenn mcdonald Avatar answered Jan 07 '23 15:01

glenn mcdonald


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
like image 34
9 revs Avatar answered Jan 07 '23 17:01

9 revs