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?
Easy:
x,y = d.sort.transpose
Or, with a custom sort:
x,y = d.sort_by {|k,v| whatever}.transpose
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With