0

在我的 ruby​​ 代码中,我遇到了“无法将字符串转换为整数”错误。代码是:

require 'rubygems'
require 'oauth'
require 'json'

# Now you will fetch /1.1/statuses/user_timeline.json,
# returns a list of public Tweets from the specified
# account.


  baseurl = "https://api.twitter.com"
path    = "/1.1/statuses/user_timeline.json"
query   = URI.encode_www_form(
    "q" => "Obama"
    "count" => 1
    )
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri

# Print data about a list of Tweets
def print_timeline(tweets)
  tweets.each do |tweet|
  require 'date'
   d = DateTime.parse(tweet['created_at'])
    puts " #{tweet['text'].delete ","} , #{d.strftime('%d.%m.%y')} , #{tweet['user']   ['name']}, #{tweet['id']}"
  end
end

# Set up HTTP.
http             = Net::HTTP.new address.host, address.port
http.use_ssl     = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

# If you entered your credentials in the first
# exercise, no need to enter them again here. The
# ||= operator will only assign these values if
# they are not already set.
consumer_key = OAuth::Consumer.new(
    "")
access_token = OAuth::Token.new(
    "")

# Issue the request.
request.oauth! http, consumer_key, access_token
http.start
response = http.request request

# Parse and print the Tweet if the response code was 200
tweets = nil

puts "Text,Date,Name,id"
if response.code == '200' then
  tweets = JSON.parse(response.body)
  print_tweets(tweets)
end
nil

调试后,我相信错误来自第 19 或 20 行(d = 和 puts 语句)。我不确定什么 String 正在尝试转换为整数。

4

1 回答 1

1

看起来您正在尝试访问tweet['created_at'],而 tweet 不是哈希结构。您应该尝试检查tweet( 也可能是tweets) 的结构。

您可以使用tweet.class或直接检查该类:tweet.inspect

我猜tweet是一个数组,因此应该使用整数而不是字符串来调用它的元素

于 2013-06-18T15:09:49.587 回答