1. Home
  2. Computing & Technology
  3. Ruby

How to Use the Twitter Gem for Ruby
Twittering With Ruby

By , About.com Guide

Using the Twitter Gem

John Nunemaker has wrapped all the Twitter goodness of Ruby into a Gem called (aptly enough) twitter. Using this gem, making API requests to Twitter is even easier than using the twitter method. Perhaps more importantly, the Twitter gem also parses the output for you, and gives you a very easy interface to the data.

Installing the Twitter gem is the same as installing any other gem. It doesn't need any native extensions, so you can use it anywhere.

$ sudo gem install twitter

If we re-write our previous follow example, it comes out to just 20 lines including whitespace!

#!/usr/bin/env ruby
require 'rubygems'
require 'twitter'

twitter = Twitter::Base.new( 'aboutruby', 'pass123' )

last_id = 1
while true
  timeline = twitter.timeline( :friends, :since_id => last_id )

  unless timeline.empty?
    last_id = timeline[0].id

    timeline.reverse.each do|st|
      puts "#{st.user.name} said #{st.text}"
    end

    sleep 300
  end
end

The first step is to create the twitter object. Simply construct a Twitter::Base object and give it your username and password. No surprises there.

To request a timeline, such as the friends timeline, call the timeline method. If given no options, it will request the friends timeline. However, since we want to use the since_id option, we'll have to add the :friends parameter and the :since_id hash parameter. The rest of the code is straightforward. Note how easy it is to get information from the status updates. For example, to get the ID of the latest update, just do timeline[0].id!

Even simpler is the previous example that posts a new update. This progam is all of two meaningful lines.

#!/usr/bin/env ruby
require 'rubygems'
require 'twitter'

twitter = Twitter::Base.new( 'aboutruby', 'pass123' )

twitter.update ARGV[0]

For more information about the twitter gem, see its homepage and documentation.

More Ruby Quick Tips
Explore Ruby
By Category
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Gems
  5. Twitter--How to Use the Twitter Gem for Ruby

©2009 About.com, a part of The New York Times Company.

All rights reserved.