Module: FetchIn
Class Method Summary collapse
- .fetch_in(h, *keys) ⇒ Object
-
.store_in(h, *keys_and_value, &proc) ⇒ Object
store_in stores a value in a nested associative structure new levels in the structure are created as required, by the supplied Proc.
Instance Method Summary collapse
- #fetch_in(*keys) ⇒ Object
-
#store_in(*keys_and_value, &proc) ⇒ Object
store_in stores a value in a nested associative structure new levels in the structure are created as required, by the supplied Proc.
Class Method Details
.fetch_in(h, *keys) ⇒ Object
3 4 5 6 7 8 |
# File 'lib/fetch_in.rb', line 3 def fetch_in(h, *keys) keys.reduce(h) do |result,key| return nil if !result result[key] end end |
.store_in(h, *keys_and_value, &proc) ⇒ Object
store_in stores a value in a nested associative structure new levels in the structure are created as required, by the supplied Proc. if no Proc is supplied, new levels are created with the same class as the previous level
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/fetch_in.rb', line 14 def store_in(h, *keys_and_value, &proc) proc ||= lambda{|rx_key_stack| rx_key_stack[-1][0].class.new} keys = keys_and_value[0..-2] value = keys_and_value[-1] # find or create the last associative receiver in the chain to the value last_rx = keys[0..-2].reduce([h,[]]) do |(rx,rx_key_stack),key| rx_key_stack = rx_key_stack << [rx,key] rx[key] = proc.call(rx_key_stack) if !rx[key] [rx[key], rx_key_stack] end[0] # set the value last_rx[keys[-1]]=value end |
Instance Method Details
#fetch_in(*keys) ⇒ Object
31 32 33 |
# File 'lib/fetch_in.rb', line 31 def fetch_in(*keys) FetchIn.fetch_in(self, *keys) end |
#store_in(*keys_and_value, &proc) ⇒ Object
store_in stores a value in a nested associative structure new levels in the structure are created as required, by the supplied Proc. if no Proc is supplied, new levels are created with the same class as the previous level
39 40 41 |
# File 'lib/fetch_in.rb', line 39 def store_in(*keys_and_value, &proc) FetchIn.store_in(self, *keys_and_value, &proc) end |