2012-02-15 117 views
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"] 

回答

3

要調用readlocal_file,這是包含字符串文件名。我打算用my_local_file.read來使用從open得到的IO對象。 (...或File.read local_file。)

不是說這是最好的形式:你爲什麼要寫一個臨時文件?你有內存中的數據,所以直接傳遞它。

如果你想寫入本地文件,我讚揚塊從公開的:

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

這樣紅寶石將關閉該文件爲你和所有的照顧。

相關問題