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
}
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.
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