0

Twitter ユーザーの xml フィードをファイルに保存してから、再度解析して画面に表示しようとしています。

これは、実行しようとすると表示されるものです..

    Wrote to file #<File:0x000001019257c8>
Now parsing user info..
twitter_stats.rb:20:in `<main>': undefined method `read' for "keva161.txt":String (NoMethodError)

これが私のコードです...

require "open-uri"
require "rubygems"
require "crack"

twitter_url = "http://api.twitter.com/1/statuses/user_timeline.xml?cout=100&screen_name="
username = "keva161"
full_page = twitter_url + username
local_file = username + ".txt"

tweets = open(full_page).read

my_local_file = open(local_file, "w")
  my_local_file.write(tweets)

puts "Wrote to file " + my_local_file.to_s
sleep(1)
puts "Now parsing user info.."
sleep(1)

parsed_xml = Crack::XML.parse(local_file.read)

tweets = parsed_xml["statuses"]

first_tweet = tweets[0]
user = first_tweets["user"]

puts user["screen_name"]
puts user ["name"]
puts users ["created_at"]
puts users ["statuses_count"]
4

1 に答える 1

3

You are calling read on local_file, which is the string containing the filename. You meant to type my_local_file.read, I guess, to use the IO object you got from open. (...or File.read local_file.)

Not that this is the best form: why are you writing to a temporary file anyhow? You have the data in memory, so just pass it directly.

If you do want to write to a local file, I commend the block from of open:

open(local_file, 'w') do |fh|
  fh.print ...
end

That way Ruby will take care of closing the file for you and all that.

于 2012-02-15T07:37:15.810 に答える