You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Ruby生成YAML时嵌套数组以方括号行内格式而非缩进列表输出

解决Ruby on Rails生成YAML时嵌套数组输出方括号格式的问题

问题原因

Ruby默认的to_yaml方法会将嵌套数组序列化为YAML块式序列(多横线缩进格式),你期望输出的方括号格式属于YAML流式序列,两种格式语义完全等价,YAML解析器读取后得到的数据结构完全一致,仅显示风格不同。

解决方案

替换默认的to_yaml调用,使用Ruby内置的YAML处理库Psych的dump方法,通过flow_level参数控制序列的输出格式:

File.open("config/ldap/#{Rails.env}.yml", "w") do |file|
  data = {}

  formatted_groups_array = []
  Setting.ldap_users_filter_required_groups.each do |group| 
    formatted_groups_array.push([Setting.ldap_group_membership_attribute.to_s, group.to_s])
  end
  data["required_groups"] = formatted_groups_array

  # flow_level设为2代表2层以内的序列都使用流式方括号格式
  yaml_content = Psych.dump(data, flow_level: 2)
  file.write(yaml_content)
end

效果验证

修改后生成的YAML就会是你期望的方括号嵌套数组格式:

required_groups:
- ["member", "cn=serviceboard-users,cn=groups,cn=accounts,dc=int,dc=dostack,dc=io"]

内容的提问来源于stack exchange,提问作者Miroslav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:36:07