为什么只有第一个链接被提取?

问题描述:

我试图从黑客新闻中获取新闻并将链接的标题和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

在这种情况下,你不应该使用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