如何在 ruby​​ 模板中输出排序的哈希

编程入门 行业动态 更新时间:2024-10-21 19:04:01
本文介绍了如何在 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​​ 模板中输出排序的哈希

本文发布于:2023-11-22 05:40:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616177.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   如何在   ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!