Last active
October 25, 2021 20:16
-
-
Save westonganger/53b098b5de488d3f57c38d85dc4fc10b to your computer and use it in GitHub Desktop.
Ruby Hash deep_set
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
| Hash.class_eval do | |
| def deep_set(keys_array, val) | |
| keys_array[0...-1].inject(self){|result, key| | |
| if !result[key].is_a?(Hash) | |
| result[key] = {} | |
| end | |
| result[key] | |
| }.send(:[]=, keys_array.last, val) | |
| return self | |
| end | |
| end | |
| h = {} | |
| h.deep_set([:foo, :bar, :asd], "foobar") | |
| h # => { foo: { bar: { asd: "foobar" } } } |
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
| class Helper | |
| def self.deep_set(hash, keys_array, val) | |
| if !hash.is_a?(::Hash) | |
| raise TypeError.new("Invalid object passed to #{__method__}, must be a Hash") | |
| end | |
| keys_array[0...-1].inject(hash){|result, key| | |
| if !result[key].is_a?(Hash) | |
| result[key] = {} | |
| end | |
| result[key] | |
| }.send(:[]=, keys_array.last, val) | |
| return hash | |
| end | |
| end | |
| h = {} | |
| Helper.hash_deep_set(h, [:foo, :bar, :asd], "foobar") | |
| h # => { foo: { bar: { asd: "foobar" } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment