加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中将嵌套哈希转换成点分隔字符串的单线程?

发布时间:2020-12-17 01:48:33 所属栏目:百科 来源:网络整理
导读:在 Ruby中将YAML转换为点分隔字符串的最简单方法是什么? 所以这: root: child_a: Hello child_b: nested_child_a: Nesting nested_child_b: Nesting Again child_c: K 对此: { "ROOT.CHILD_A" = "Hello","ROOT.CHILD_B.NESTED_CHILD_A" = "Nesting","ROOT
在 Ruby中将YAML转换为点分隔字符串的最简单方法是什么?

所以这:

root:
  child_a: Hello
  child_b:
    nested_child_a: Nesting
    nested_child_b: Nesting Again
  child_c: K

对此:

{
  "ROOT.CHILD_A" => "Hello","ROOT.CHILD_B.NESTED_CHILD_A" => "Nesting","ROOT.CHILD_B.NESTED_CHILD_B" => "Nesting Again","ROOT.CHILD_C" => "K"
}

解决方法

它不是单行,但它可能符合您的需求

def to_dotted_hash(source,target = {},namespace = nil)
  prefix = "#{namespace}." if namespace
  case source
  when Hash
    source.each do |key,value|
      to_dotted_hash(value,target,"#{prefix}#{key}")
    end
  when Array
    source.each_with_index do |value,index|
      to_dotted_hash(value,"#{prefix}#{index}")
    end
  else
    target[namespace] = source
  end
  target
end

require 'pp'
require 'yaml'

data = YAML.load(DATA)
pp data
pp to_dotted_hash(data)

__END__
root:
  child_a: Hello
  child_b:
    nested_child_a: Nesting
    nested_child_b: Nesting Again
  child_c: K

版画

{"root"=>
      {"child_a"=>"Hello","child_b"=>{"nested_child_a"=>"Nesting","nested_child_b"=>"Nesting Again"},"child_c"=>"K"}}
    {"root.child_c"=>"K","root.child_b.nested_child_a"=>"Nesting","root.child_b.nested_child_b"=>"Nesting Again","root.child_a"=>"Hello"}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读