如何在 ruby​​ 模板中输出排序的哈希 [英] How to output sorted hash in ruby template

查看:50
本文介绍了如何在 ruby​​ 模板中输出排序的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们的一个内联应用程序构建一个配置文件.它本质上是一个json文件.我在让 puppet/ruby 1.8 每次都以相同的方式输出哈希/json 时遇到了很多麻烦.

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.

我目前正在使用

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

但是在输出人类可读的内容时,它并不能保证每次都具有相同的顺序.这意味着 puppet 会经常为相同的数据发送更改通知.

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.

我也试过

<%= 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", ] }

变成

"beanstalkd": "server1",

代替

"beanstalkd": ["server1"],

我已经断断续续地与这个问题斗争了几天,所以需要一些帮助

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

推荐答案

Hash 是一种无序数据结构.在某些语言(例如 ruby​​)中,有一个有序版本的哈希,但在大多数情况下,在大多数语言中,你不应该依赖哈希中的任何特定顺序.

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}

变成这样

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

我认为,它不会强制对您的代码进行太多更改.

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

试试这个:

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}

这篇关于如何在 ruby​​ 模板中输出排序的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆