Skip to content

Instantly share code, notes, and snippets.

@grdscrc
Last active June 18, 2019 14:59
Show Gist options
  • Select an option

  • Save grdscrc/c3fc57b597e0c35cfc3efe9643c7816c to your computer and use it in GitHub Desktop.

Select an option

Save grdscrc/c3fc57b597e0c35cfc3efe9643c7816c to your computer and use it in GitHub Desktop.

Revisions

  1. grdscrc revised this gist Jun 18, 2019. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion hash_node_lineages.rb
    Original file line number Diff line number Diff line change
    @@ -18,7 +18,9 @@ def node_lineages
    end
    end

    self.map(&:reduce_to_node)
    self.map do |key, value|
    reduce_to_node.call(key, value)
    end
    end
    end

  2. grdscrc created this gist Jun 18, 2019.
    56 changes: 56 additions & 0 deletions hash_node_lineages.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #!/usr/bin/env ruby

    class Hash
    def node_lineages
    reduce_to_node = Proc.new do |prefix_key,value|
    if value.is_a?(Hash)
    value.map do |child_key,child_value|
    new_prefix = [prefix_key,child_key].join('.')
    reduce_to_node.call(new_prefix,child_value)
    end
    elsif value.is_a?(Array)
    value.map do |child_item|
    new_prefix = "#{prefix_key}[]"
    reduce_to_node.call(new_prefix, child_item)
    end
    else
    [prefix_key, value].join('=')
    end
    end

    self.map(&:reduce_to_node)
    end
    end

    hash = { a: :b }
    expected = 'a=b'
    actual = hash.node_lineages
    raise "Test failed : #{expected.inspect} expected, #{actual.inspect} actual" unless actual == expected

    hash = { a: { b: :c, d: :e } }
    expected = "a.b=c ; a.d=e"
    actual = hash.node_lineages.join(';')
    raise "Test failed : #{expected.inspect} expected, #{actual.inspect} actual" unless actual == expected

    hash = {
    a: {
    b: :c,
    d: :e
    },
    f: [
    :g,
    :h,
    :i
    ]
    }
    expected = <<-HEREDOC
    a.b=c
    a.d=e
    f[]=g
    f[]=h
    f[]=i
    HEREDOC
    actual = hash.node_lineages.join("\n")
    raise "Test failed : #{expected.inspect} expected, #{actual.inspect} actual" unless actual == expected

    puts 'All tests OK :)'