README.md in depth-0.1.0 vs README.md in depth-0.3.0
- old
+ new
@@ -69,10 +69,14 @@
{ '#otherfeed' => {'thing' => [] } },
]}
]}
route = ['$and', 1, '$or', 0, '#otherfeed', 'thing']
Depth::ComplexHash.new(hash).find(route) # => []
+
+ # Or with a default
+ Depth::ComplexHash.new(hash).find(%w(not a route), default: 'hello') # => 'hello'
+
```
But there's something cool hidden in the `set` message,
if part of the structure is missing, it'll fill it in as it
goes, e.g.:
@@ -104,26 +108,65 @@
# Routes can also be defined in other ways
route = ['$and', 1, '$or', 0, { key: '#sup', type: :array }, 0]
route = ['$and', 1, '$or', 0, RouteElement.new('#sup', type: :array), 0]
```
+Find can also perform the same magic if you set the keyword
+argument `create` to be true. A default value can also be supplied:
+
+```ruby
+ hash = { '$and' => [
+ { '#weather' => { 'something' => [], 'thisguy' => 4 } },
+ { '$or' => [
+ { '#otherfeed' => {'thing' => [] } },
+ ]}
+ ]}
+ route = ['$and', 1, '$or', 0, '#sup', 'thisthing']
+ Depth::ComplexHash.new(hash).find(route, create: true)
+ puts hash.inspect #=>
+ # hash = { '$and' => [
+ # { '#weather' => { 'something' => [], 'thisguy' => 4 } },
+ # { '$or' => [
+ # { '#otherfeed' => {'thing' => [] } },
+ # { '#sup' => { } },
+ # ]}
+ # ]}
+
+ # Or if you supply a default value as well
+ val = Depth::ComplexHash.new(hash).find(route, create: true, default: 'blargle')
+ puts val #=> 'blargle'
+ puts hash.inspect #=>
+ # hash = { '$and' => [
+ # { '#weather' => { 'something' => [], 'thisguy' => 4 } },
+ # { '$or' => [
+ # { '#otherfeed' => {'thing' => [] } },
+ # { '#sup' => { 'thisthing' => 'blargle' } },
+ # ]}
+ # ]}
+```
### Enumeration
The messages signatures relating to enumeration are:
* `each` = yields `key_or_index` and `fragment`, returns the complex hash
* `select` = yields `key_or_index`, `fragment`, returns a new complex hash
* `reject` = yields `key_or_index`, `fragment`, returns a new complex hash
* `map` = yields `key_or_index`, `fragment` and `parent_type`, returns a new complex hash
* `map_values` = yields `fragment`, returns a new complex hash
* `map_keys` = yields `key_or_index`, returns a new complex hash
-* `map!`, `map_keys!` and `map_keys_and_values!`, returns a new complex hash
+* `map!`, `map_keys!` and `map_keys_and_values!`, returns the base complex hash
* `reduce(memo)` = yields `memo`, `key` and `fragment`, returns memo
* `each_with_object(obj)` = yields `key`, `fragment` and `object`, returns object
_Fragment refers to a chunk of the original hash_
These, perhaps, require a bit more explanation:
+
+_NB_ All of these methods yield an argument at the end
+which is the route taken to get to this fragment of the hash,
+I've not detailed the use of it here because it's rarely necessary but
+it's available in case you have some complex map rules that change
+based on where you are in the hash.
#### each
The staple, and arguably the most important, of all the enumeration methods,