Skip to content

Instantly share code, notes, and snippets.

@yalab
Created October 16, 2019 05:31
Show Gist options
  • Save yalab/f6d37cddd7bfbae11440532c0c1e6a6e to your computer and use it in GitHub Desktop.
Save yalab/f6d37cddd7bfbae11440532c0c1e6a6e to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'yaml'
def yaml_to_scalar(node, anchors={})
case node
when Psych::Nodes::Scalar
node.value
when Psych::Nodes::Document
node.children.map do |child|
yaml_to_scalar(child, anchors)
end
when Psych::Nodes::Mapping
hash = {}
node.children.each_slice(2) do |key, value|
k = yaml_to_scalar(key, anchors)
v = yaml_to_scalar(value, anchors)
if k == '<<'
hash = hash.merge(v)
else
hash[k] = v
end
end
anchors[node.anchor] = hash if a = node.anchor
hash
when Psych::Nodes::Sequence
ary = []
node.children.each do |child|
ary << yaml_to_scalar(child, anchors)
end
anchors[node.anchor] = ary if a = node.anchor
ary
when Psych::Nodes::Alias
anchors[node.anchor]
else
node
end
end
pp yaml_to_scalar(YAML.parse(ARGF.read)).first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment