Created
October 17, 2016 23:33
-
-
Save aschyiel/04136beaaede45b695b97b4cb3cc2b96 to your computer and use it in GitHub Desktop.
A ruby analog of lodash#get.
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
module MyModuleName | |
# Safely navigate a hashmap via dot-notation, similar to lodash#get. | |
# May return nil; Assumes string keys, will not work for symbols! | |
# | |
# Example Usage: | |
# got(foo, 'bar.fizz.buzz') | |
def got(object, dot_notation_path, default_value = nil) | |
# FIXME: Does not support OpenStruct! -uly, july 2016 | |
keys = dot_notation_path.split('.') | |
while !keys.empty? && !object.nil? | |
object = object.is_a?(Array) ? nil : object.try(:fetch, keys.shift, nil) | |
end | |
object.nil? ? default_value : object | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://lodash.com/docs/4.16.4#get