nested-collections
# Metadata
2022-06-04 18:50 | nested-collections | Doriel Rivalet
# Content
use #dig to about errors when indexing arrays/hashes
This first example uses the second optional argument for the default value.
|
|
Changing the value of the first element in the first nested array, causes the first element to change in all three nested arrays! This same behavior will happen with strings, hashes, or any other mutable objects.
Now, let’s take a look at an example that omits the second optional argument and instead passes in the mutable value in a block.
|
|
Changing the value of the first element in the first nested array does not cause the value to change in any other nested array.
if any student scored higher than 80 on everything.
|
|
What do you think will happen if we switch #any?
and #all?
? Do you think we will get the same results?
|
|
The results are different, because now it is determining if all of the nested arrays contain any number over 80. This returns true, because each of the nested arrays have at least one number over 80.
|
|
#select, #filter, #collect/map, #compact
|
|
|
|
Ruby provides a couple of tools to help us comprehend arrays, hashes, and nested mixtures of both.
Assuming your data looks like this (I’ve added quotes around GOOG
and FB
):
|
|
You can iterate over the array using
each
, e.g.:
|
|
Digging into a hash and printing the result can be done in a couple of ways:
|
|
Method #1 uses the
hash[key]
syntax, and because the first hash value is another hash, it can be chained to get the result you’re after. The drawback of this approach is that if you have a missing properties
key on one of your results, you’ll get an error.
Method #2 uses
dig
, which accepts the nested keys as arguments (in order). It’ll dig down into the nested hashes and pull out the value, but if any step is missing, it will return nil
which can be a bit safer if you’re handling data from an external source
# Removing elements from a hash
Your second question is a little more involved. You’ve got two options:
- Remove the
primary_role
keys from the nested hashes, or - Create a new object which contains all the data except the
primary_role
keys.
I’d generally go for the latter, and recommend reading up on immutability and immutable data structures.
However, to achieve [1] you can do an in-place
delete
of the key:
|
|
# Adding elements to a hash
You assign new hash values simply with
hash[key] = value
, so you can set the industry with something like:
|
|
which would leave you with something like:
|
|
reminder: switch from if !
to unless
# Sources
Own notes
https://www.theodinproject.com/lessons/ruby-nested-collections
https://learn.co/lessons/nested-hash-iteration
# Content Lists
If you prefer browsing the contents of this site through a list instead of a graph, you can find content lists here too: