Skip to content

Instantly share code, notes, and snippets.

@acallaghan
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save acallaghan/ae104160d9e888a7ee41 to your computer and use it in GitHub Desktop.

Select an option

Save acallaghan/ae104160d9e888a7ee41 to your computer and use it in GitHub Desktop.
A ruby snippet to recombine an array representing a stack of markup, outputting an orderly stack in parent/child relationship
=begin
<px:categories>
<px:each>
<px:category>
<px:books>
<px:each>
<px:book>
--- Get stack suggestions at this level
=end
stack = [nil, 'categories', 'each', 'category', 'books', 'each', 'book']
limit = stack.size
limit = 3 if stack.size > 3
combinations = 1.upto(limit).flat_map {|n|
stack.compact.combination(n).to_a.reject!{ |a| a[0] == 'each' }
}.compact
pp combinations
[["categories"],
["category"],
["books"],
["book"],
["categories", "each"],
["categories", "category"],
["categories", "books"],
["categories", "each"],
["categories", "book"],
["category", "books"],
["category", "each"],
["category", "book"],
["books", "each"],
["books", "book"],
["categories", "each", "category"],
["categories", "each", "books"],
["categories", "each", "each"],
["categories", "each", "book"],
["categories", "category", "books"],
["categories", "category", "each"],
["categories", "category", "book"],
["categories", "books", "each"],
["categories", "books", "book"],
["categories", "each", "book"],
["category", "books", "each"],
["category", "books", "book"],
["category", "each", "book"],
["books", "each", "book"]]
pp combinations.collect{ |a| "px:#{a.join(':')}" }
["px:categories",
"px:category",
"px:books",
"px:book",
"px:categories:each",
"px:categories:category",
"px:categories:books",
"px:categories:each",
"px:categories:book",
"px:category:books",
"px:category:each",
"px:category:book",
"px:books:each",
"px:books:book",
"px:categories:each:category",
"px:categories:each:books",
"px:categories:each:each",
"px:categories:each:book",
"px:categories:category:books",
"px:categories:category:each",
"px:categories:category:book",
"px:categories:books:each",
"px:categories:books:book",
"px:categories:each:book",
"px:category:books:each",
"px:category:books:book",
"px:category:each:book",
"px:books:each:book"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment