Lesson content is currently in draft form.
In the last chapter we parsed a JSON file containing Twitter account information.
But what does that mean, exactly?
Run the routine again to fetch the info for a Twitter account:
1 2 3 4 5 6 7 |
|
Note: The rest of this lesson assumes that twitter_user
contains the value that it does at the end of this routine. If you exit and relaunch irb, just re-run this routine to follow along again.
What is the class
of the parsed JSON?
1 2 |
|
The Hash Object
The Hash
is one of Ruby’s collection classes and is ubiquitous in Ruby coding (in Python, it’s called a dictionary).
Collection classes are data objects that are collections of other data objects (so yes, this means a Hash
can contain many other Hash
objects).
Here’s how a simple Hash
object is initialized:
1
|
|
- The curly-braces denote the entire
Hash
. - Hashes are composed of key-value pairs
- This
simple_hash
has only one item, i.e. one key-value pair - The key in that single pair is on the left side:
'a'
. The value is on the right, i.e. 101
Accessing members of a Hash
To access an item in a Hash
, we use square-bracket notation to specify the key of the value that we want.
1 2 3 |
|
Try it yourself. In the Hash
below:
1. Print out the value at key 42
2. Access the pair with the value of "dog"
and store the value (i.e. "dog"
) in a variable
1 2 3 4 5 6 7 |
|
Exercise
Go back to the twitter_user
object, which we initialized at the beginning of this lesson. Print out:
- The user’s real name
- The user’s Twitter bio
- The user’s number of followers
Hint: Printing out the twitter_user
object might be helpful here.
Answer
1 2 3 4 5 6 7 8 |
|
Bonus: What happens when you try to access a non-existent key?