簡體   English   中英

如何將符號轉換為字符串(即帶狀開頭:) ruby​​ to_yaml

[英]How to convert symbols to strings (i.e. strip leading :) ruby to_yaml

我正在嘗試從我的YAML輸出中刪除前導: 這是代碼,下面是我做的:

模型/ attribution_channel.rb

DEFAULT_BONUS_CONFIG =  {
  sign_up: {
    currency: 'ngn',
    type: 'flat',
    amount: 1000
  },
  visit: {
    currency: 'ngn',
    type: 'flat',
    amount: 5
  }
}

視圖/ form.slim.html

AttributionChannel::DEFAULT_BONUS_CONFIG.to_yaml

輸出:

產量

要從輸出中刪除YAML分隔符---Leading:,請執行以下操作:

AttributionChannel::DEFAULT_BONUS_CONFIG.to_yaml.gsub("---\n", '').sub(":", '')

..但該.sub(":", '')部分僅除去:第一領先的:

如何從YAML輸出中刪除前導: 任何幫助表示贊賞嗎? 這是我想要的以下內容:

sign_up:
  currency: ngn
  type: flat
  amount: 1000
visit:
  currency: ngn
  type: flat
  amount: 5

您需要將鍵作為字符串跳過:生成

require 'active_support/core_ext/hash/keys'
require 'yaml'

DEFAULT_BONUS_CONFIG.deep_stringify_keys.to_yaml.gsub("---\n", '')

 => "sign_up:\n  currency: ngn\n  type: flat\n  amount: 1000\nvisit:\n  currency: ngn\n  type: flat\n  amount: 5\n"

您可以在生成YAML之前將哈希鍵轉換為字符串。 下面的代碼經過哈希處理,將每個鍵遞歸地轉換為哈希,如果是哈希,則對每個值進行字符串化處理(請注意,它沒有為哈希中的循環依賴做好准備)。

def stringify(hash)
  hash.map{|k, v| [k.to_s, v.is_a?(Hash) ? stringify(v) : v] }.to_h
end  

puts stringify(DEFAULT_BONUS_CONFIG).to_yaml

---
sign_up:
  currency: ngn
  type: flat
  amount: 1000
visit:
  currency: ngn
  type: flat
  amount: 5

編輯:關於---一開始,請參閱此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM