2012-04-20 77 views
1

我試圖從黑客新聞中獲取新聞並將鏈接的標題和URL寫入HTML文件。但是,只有第一個鏈接正在寫入,而其他鏈接則不是。我究竟做錯了什麼?爲什麼只有第一個鏈接被提取?

require 'httparty' 

def fetch(source) 
    response = HTTParty.get(source) 
    response["items"].each do |item| 
    return '<a href="' + item["url"] + '">' + item["title"] + '</a>' 
    end 
end 

links = fetch('http://api.ihackernews.com/page') 

File.open("/tmp/news.html", "w") do |f| 
    f.puts links 
end 
+0

我冒昧,並改寫你的問題的標題,以更好地反映正在發生的事情的代碼。 – 2012-04-20 22:33:26

回答

4

在這種情況下,你不應該使用return關鍵字。它過早地結束該方法並僅返回第一個鏈接。使用這個來代替:

require 'httparty' 

def fetch(source) 
    response = HTTParty.get(source) 

    # convert response['items'] array to array of strings 
    response["items"].map do |item| 
    '<a href="' + item["url"] + '">' + item["title"] + '</a>' 
    end 
end 

links = fetch('http://api.ihackernews.com/page') 

links.length # => 30 
+0

謝謝!這工作。但是,SO說我必須等5分鐘才能接受它作爲答案:D – Timur 2012-04-20 22:34:52

+1

沒問題,我可以等待:) – 2012-04-20 22:35:16

相關問題