Twitter API - Ruby Twitter Gem

2019-03-06 11:34发布

问题:

How can I access Twitter::Cursor hash values returned by the Twitter API?

I am following the Jumpstartlab Microblogger tutorial for using the Twitter gem via the jumpstart_auth gem.

I am on iteration 4 step 1. I can return a friends object with the following code:

def friends_last_tweets
  friends = client.friends
  puts friends
end

=>    Twitter::Cursor:0x00000104051928

However, the example account, 'client' in this case, has two 'friends' not just one so why does it only return one object? I thought maybe that object is the array or arrays with all of the friends accordingly in hash values within, thus use [] to access, but this returns "undefined method for Twitter::Cursor". I run each on the Twitter::Cursor object and it returns two fixnums:

def friends_last_tweets
    friends = client.friends
    friends.each { |f| puts f }
end

=> 18908095
108528349

So surely these numbers must represent each 'friend object' within the Twitter::Cursor object me thinks. I need to access the key/value pairs within that object, yet my attempted hash accessing results in undefined method or variable.

In case it's version issue related, I'm using Twitter5.11.0 and Jumpstart_auth 0.6.0.

回答1:

Access the 'friends' object in the same way you accessed the 'followers' object earlier in the tutorial in order to get a list of your followers' screen names.

To get an array of followers' screen names:

screen_names = @client.followers.collect {|f| @client.user(f).screen_name }

To get an array of friends' screen names:

screen_names = @client.friends.collect {|f| @client.user(f).screen_name }

To get the last tweet of a friend, you can use the object_id's you posted above, as:

last_tweet = @client.user(object_id).status.tweet

I hope this helps. I was caught on this issue for a while too.



回答2:

those answers didn't helped me to get the last message (maybe the API changed in the meantime), that's how I finally did it:

    def everyones_last_tweet
      puts "\n\n here are the latest tweets of your friends:"
      friends = @client.friends.collect { |f| @client.user(f) }
      friends.each do |friend|
        puts "\n\n#{friend.screen_name} wrote: \n\t #{friend.status.text}"
      end
    return ""
end

I'm not happy with that return string though