Lesson content is currently in draft form.
As fun as it’s been to collect tweets from Rep. Nancy Pelosi, you probably have bigger ideas, or at least want to compare Pelosi to her peers.
Good for you; the big picture should always be considered. The problem is, the big picture takes more work.
And this is where programming with its ability to zip through repetitive steps really pays off.
Reading a simple list
You could probably look up the Twitter handles of the other Congressmembers yourself and then copy and paste them into whatever tweet-collecting program you’ve devised.
But that’s not scalable. And totally unnecessary if such a list already exists.
Here’s a sample list of ten congressmembers. It’s just a straightforward textfile with one Twitter name per line:
joebiden
RoyBlunt
senatorboxer
ChuckGrassley
DarrellIssa
JoeLieberman
RepRonPaul
jaredpolis
SenRandPaul
NancyPelosi
Wouldn’t it be nice if we could break this into an array?
Split
We know that if we HTTParty.get
that list, we’ll have a String
of text. But we don’t want one string, we want as many strings as there are lines.
So let’s use the split
method of String
. It takes in one argument: the string that you want to divide the invoking string by. It returns: an array of elements from that divided string:
1 2 3 4 5 |
|
The backslash and newline character
To get an array of Congressmember Twitter names, we need to split the sample text file by whatever character is used to create a newline, i.e. the thing that happens when we press Enter.
This is the newline character: "\n"
In Ruby strings, newlines are just characters. That backslash – \n
– before the n
– has a special meaning in Ruby (and other programming languages).
The backslash acts as an escape character, and it affects the character that immediately follows it. In this case, this is the letter n
.
In other words, \n
is not just a normal, literal n
character, but the symbol for a newline, i.e. a line break.
So, write the code to:
- Download from the URL at this link
- Separate it into an array
- Loop through the array, printing out an uppercase version of each string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Exercise
Obviously, we don’t want just the names in uppercase, we want to do something. Why don’t we combine the power of this loop with some of the functionality from last chapter’s loops?
Once you’ve gathered the names in the list, loop through the list and print the created_at
and text
of the latest tweet from each of the Twitter accounts.
(Twitter spits out the tweets in reverse chronological order. So for our purposes, this would be the first tweet in an array).
Answer
File /Users/dairy/proj/octo-code6hrs/source/downloads/code/latest-tweets.rb could not be found