Last active
September 7, 2017 02:00
-
-
Save ch1c0t/218f9f1aa0e4e0c1d0149da46a1fa225 to your computer and use it in GitHub Desktop.
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
# https://www.linux.org.ru/forum/development/13492726 | |
class Glob | |
def self.=== string | |
string.include? ?* | |
end | |
end | |
class MyHash < Hash | |
def initialize | |
@regexps, @globs = {}, {} | |
super { |hash, key| hash[key] = find_value_of key } | |
end | |
def []= key, value | |
case key | |
when Regexp | |
@regexps[key] = value | |
when Glob | |
@globs[key] = value | |
else | |
super | |
end | |
end | |
private | |
def find_value_of key | |
@regexps.find { |regexp, _value| regexp.match? key }&.last or | |
@globs.find { |glob, _value| File.fnmatch? glob, key }&.last | |
end | |
end | |
hash = MyHash.new | |
hash[/^(any|key|be|no|key)$/] = 'value' | |
hash['hello'] = 'world' | |
hash['foo*bar'] = 'Dummy staff' | |
p hash.values_at 'any', 'hello', 'foo_some_staff_in_the_middle_bar' | |
#=> ["value", "world", "Dummy staff"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment