How to output sorted hash in ruby template

无人久伴 提交于 2019-12-08 18:03:35

问题


I'm building a config file for one of our inline apps. Its essentially a json file. I'm having a lot of trouble getting puppet/ruby 1.8 to output the hash/json the same way each time.

I'm currently using

<%= require "json"; JSON.pretty_generate data %>

But while outputting human readable content, it doesn't guarantee the same order each time. Which means that puppet will send out change notifications often for the same data.

I've also tried

<%= require "json"; JSON.pretty_generate Hash[*data.sort.flatten] %>

Which will generate the same data/order each time. The problem comes when data has a nested array.

data => { beanstalkd => [ "server1", ] }

becomes

"beanstalkd": "server1",

instead of

"beanstalkd": ["server1"],

I've been fighting with this for a few days on and off now, so would like some help


回答1:


Hash is an unordered data structure. In some languages (ruby, for example) there's an ordered version of hash, but in most cases in most languages you shouldn't rely on any specific order in a hash.

If order is important to you, you should use an array. So, your hash

{a: 1, b: 2}

becomes this

[{a: 1}, {b: 2}]

I think, it doesn't force too many changes in your code.

Workaround to your situation

Try this:

data = {beanstalkId: ['server1'], ccc: 2, aaa: 3}

data2 = data.keys.sort.map {|k| [k, data[k]]}

puts Hash[data2]
#=> {:aaa=>3, :beanstalkId=>["server1"], :ccc=>2}



回答2:


Since hashes in Ruby are ordered, and the question is tagged with ruby, here's a method that will sort a hash recursively (without affecting ordering of arrays):

def sort_hash(h)
  {}.tap do |h2|
    h.sort.each do |k,v|
      h2[k] = v.is_a?(Hash) ? sort_hash(v) : v
    end
  end
end

h = {a:9, d:[3,1,2], c:{b:17, a:42}, b:2 }
p sort_hash(h)
#=> {:a=>9, :b=>2, :c=>{:a=>42, :b=>17}, :d=>[3, 1, 2]}

require 'json'
puts sort_hash(h).to_json
#=> {"a":9,"b":2,"c":{"a":42,"b":17},"d":[3,1,2]}

Note that this will fail catastrophically if your hash has keys that cannot be compared. (If your data comes from JSON, this will not be the case, since all keys will be strings.)



来源:https://stackoverflow.com/questions/9733764/how-to-output-sorted-hash-in-ruby-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!