Skip to content

Instantly share code, notes, and snippets.

@jgomo3
Last active February 28, 2018 00:03
Show Gist options
  • Save jgomo3/ac5d4d3a828c20b4b4daee84b206670e to your computer and use it in GitHub Desktop.
Save jgomo3/ac5d4d3a828c20b4b4daee84b206670e to your computer and use it in GitHub Desktop.
Returns the string after resolving all the references the strings do
# Given a table of strings, which could reference any other string in the table,
# returns the string after resolving all the references.
# Example:
# table = {a: 'ツ', b: '(%{a})', c1: '¯\_', c2: '_/¯', o: '%{c1}%{b}%{c2}'}
# explode_key(table, :o) => ¯\_(ツ)_/¯
# It doesn't allow circular references.
def explode_key(keys_table, key)
partial_string = keys_table[key]
allowed_loops = keys_table.keys.length # [1]
(1..allowed_loops).lazy.map do |i|
partial_string %= keys_table
string_slots(partial_string).empty?
end.find(->(){raise 'Circular reference in Table'}){|i| i}
partial_string
end
def string_slots(s)
slot_pattern = /%{(.+?)}/
s.scan(slot_pattern).map {|match| match[0]}
end
# [1] # https://stackoverflow.com/questions/49013761/can-we-get-the-slots-ruby-will-consider-if-interpolating-with-string-formating?noredirect=1#comment85043024_49013761
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment