Reputation: 732
I have a hash where the keys are integers and the values are arrays of strings. I need to then sort the items in the arrays alphabetically and return the sorted array as the new hash value.
I thought something like hash.map{ |k,v| v.sort }
would work, but, no. Just to be a little more explicit, I need to turn:
hash = { 0 => ["c", "d", "b", "a"], 1 => ["e", "q", "x", "m"] }
into:
hash = { 0 => ["a", "b", "c", "d"], 1 => ["e", "m", "q", "x"] }
Upvotes: 1
Views: 559
Reputation: 110675
This does not mutate the original hash.
hash.merge(hash) { |*,n| n.sort }
#=> {0=>["a", "b", "c", "d"], 1=>["e", "m", "q", "x"]}
If the original hash is to be modified, substitute merge!
(aka update
) for merge
.
This uses the forms of Hash#merge and Hash#merge! that employ a block to determine the values of keys that are present in both hashes being merged, which here is all keys of the original hash. See the docs for details.
Upvotes: 0
Reputation: 9497
This is one way:
hash.each_value { |v| v.sort! }
#=> {0=>["a", "b", "c", "d"], 1=>["e", "m", "q", "x"]}
or more succinctly:
hash.each_value(&:sort!)
However if you wish to preserve the original hash do this:
hash.map { |k,v| [k,v.sort] }.to_h
#=> {0=>["a", "b", "c", "d"], 1=>["e", "m", "q", "x"]}
Upvotes: 4
Reputation: 27793
Try this,
hash.each { |k,v| v.sort! }
This sorts the arrays in-place.
Upvotes: 2