Last active
February 28, 2018 00:03
-
-
Save jgomo3/ac5d4d3a828c20b4b4daee84b206670e to your computer and use it in GitHub Desktop.
Returns the string after resolving all the references the strings do
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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