tee
tee

Reputation: 4429

Sort hash elements in-place within an array

I have an array. Some elements are hashes. I want to sort the hashes in-place and leave the array elements in order.

Can I improve this code?

def sort(args)
  args.map! do |arg|
    arg.is_a?(Hash) ? arg.sort : arg
  end
end

For example:

sort [{"b"=>"2", "a"=>"1"}, "x"]
=> [{"a"=>"1", "b"=>"2"}, "x"]

Upvotes: 0

Views: 111

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

AFAIU your question is how to sort a hash inplace, since you don’t need any modifications to original array but those. To sort a Hash inplace you might use:

hash.keys.sort.each { |k| hash[k] = hash.delete k }

Putting it all together:

def sort args
  args.each { |el|
    el.keys.sort.each {|k|
      el[k] = el.delete k
    } if Hash === el
  }
end

res = sort [{"b"=>"2", "a"=>"1"}, "x"]
puts res 
# ⇒ [{"a"=>"1", "b"=>"2"}, "x"]

Hope it helps.

Upvotes: 1

Related Questions