Expand Your Twitter Network In Less Than 15 Lines of Ruby
17 May 2009
A great way to meet new people on Twitter is by checking out the people your friends are interacting with. We can assume that if many of your friends follow somebody, that person has a high likelihood of being interesting to you (or it is Ashton Kutcher). Let’s use Ruby to generate a list of people highly followed by our friends.
The Flow
- fetch the ids of all the people you follow
- use those ids to fetch the ids of all the people they follow
- remove any ids in both groups (sound familiar?)
- tally the occurrences of each unique id in the list
- sort them by most occurrences
- iterate the top 10 and print the user information
The Script
require 'rubygems'
require 'twitter'
base = Twitter::Base.new(Twitter::HTTPAuth.new('username', 'password'))
my_friends = base.friend_ids
candidates = my_friends.inject(Array.new) { |array,id| array += Twitter.friend_ids(id); array }
candidates -= my_friends
tallied = candidates.inject(Hash.new(0)) { |hash, can| hash[can] += 1; hash }
ordered = tallied.sort { |x,y| y[1] <=> x[1] }
ordered[0..9].each do |array|
user = base.user(array[0])
puts "#{user.screen_name} is followed by #{array[1]} of people you follow."
end
Some Explanation
The only “tricky” thing I’m doing is making good use of Ruby’s Enumerable#inject method. Twice. This method iterates an enumerable object similar to how each
does except it takes an argument and passes it through the block with the object it is iterating. The variable passed can be modified and is returned by the method. For a good write-up on inject
, see this blog post by The Budding Rubyist.
A Limitation
Unfortunately, this script is hindered by Twitter’s 100 API calls per hour. If you follow more than 100 people on Twitter you’re going to need a workaround. I’ll leave these as an exercise for whoever is interested, but a few ideas are:
- sleep the script between API hits
- toggle between multiple accounts for requests
- request whitelisting from Twitter
A Challenge
Can you can make this script smaller, more readable, or more robust? I put it on GitHub so you can fork my gist and put a link to your version in the comments!