Last active
February 1, 2019 08:20
-
-
Save dmitryck/3a0fe25e9a46e000e82e26b54b4207cc to your computer and use it in GitHub Desktop.
Path-like accessing to hash nodes
This file contains 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
TARGET = 4 | |
INPUT = { | |
a: { | |
b: { | |
c: TARGET | |
} | |
} | |
} | |
PATH = 'a.b.c' | |
module Solution | |
VARIANTS = { | |
eval: ->{ eval 'INPUT[:' + keys.join('][:') + ']' }, | |
reduce: ->{ keys.map(&:to_sym).reduce(INPUT, :[]) } | |
# feel free to put another here | |
} | |
def self.keys | |
@@keys ||= PATH.split('.') | |
end | |
def self.results | |
VARIANTS.map do |name, l| | |
begin | |
{ name => l.call } | |
rescue StandardError => e | |
{ name => [e.message, e.backtrace[0]] } | |
end | |
end | |
end | |
def self.values | |
results.map{|h| h.values[0]} | |
end | |
def self.check! | |
(values - [TARGET]).empty? | |
end | |
end | |
# true - good, false - bad.. | |
puts Solution.check! | |
# if need trace | |
puts Solution.results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment