Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort hash keys based on array keys?

Tags:

ruby

There is an example of a hash:

h1 = {
  a1: :a2,
  b1: :b2,
  c1: :c2,
  d1: :d2,
  e1: :e2,
  f1: :f2
}

And there is such an array of keys:

a1 = [:b1, :d1, :f1]

How to sort the keys of this hash based on the array? The hash keys that are not in the array must come after the sorted ones in the order in which they were.

Result:

{
  b1: :b2,
  d1: :d2,
  f1: :f2,
  a1: :a2,
  c1: :c2,
  e1: :e2
}
like image 889
Colibri Avatar asked Dec 13 '25 11:12

Colibri


1 Answers

I would do this:

h1.slice(*a1).merge(h1.except(*a1))
#=> {:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}

Hash#slice returns the elements from h1 in the order how they are defined in a1. And the Hash#except returns the missing ones. And Hash#merge merges both groups into one hash.

like image 90
spickermann Avatar answered Dec 15 '25 12:12

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!