在数组中就地对哈希元素进行排序

时间:2021-07-10 15:55:55

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"]

1 个解决方案

#1


1  

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:

AFAIU您的问题是如何对哈希进行排序,因为您不需要对原始数组进行任何修改。要对Hash进行排序,您可以使用:

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.

希望能帮助到你。

#1


1  

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:

AFAIU您的问题是如何对哈希进行排序,因为您不需要对原始数组进行任何修改。要对Hash进行排序,您可以使用:

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.

希望能帮助到你。