I’ve been pulling data from an API in JSON, and am currently stumbling over an elmementary problem
The data is on companies, like Google and Facebook, and is in an array or hashes, like so:
[
{"id"=>"1", "properties"=>{"name"=>"Google", "stock_symbol"=>GOOG, "primary_role"=>"company"}},
{"id"=>"2", "properties"=>{"name"=>"Facebook", "stock_symbol"=>FB, "primary_role"=>"company"}}
]
Below are two operations I’d like to try:
- For each company, print out the name, ID, and the stock symbol (i.e. “Google – 1 – GOOG” and “Facebook – 2 – FB”)
- Remove “primary role” key/value from Google and Facebook
- Assign a new “industry” key/value for Google and Facebook
Any ideas?
Am a beginner in Ruby, but running into issues with some functions / methods (e.g. undefined method) for arrays and hashes as this looks to be an array OF hashes
Thank you!
2
Answers
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
andFB
):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 missingproperties
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 returnnil
which can be a bit safer if you’re handling data from an external sourceRemoving elements from a hash
Your second question is a little more involved. You’ve got two options:
primary_role
keys from the nested hashes, orprimary_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:
To achieve the first operation, you can iterate through the array of companies and access the relevant information for each company. Here’s an example in Ruby:
This will print out the name, ID, and stock symbol for each company.
To remove the "primary role" key/value, you can use the delete method on the properties hash. For example:
To add a new "industry" key/value, you can use the []= operator to add a new key/value pair to the properties hash. For example:
This will add a new key/value pair with the key "industry" and the value "Technology" to the properties hash for each company.