我正在尝试从 Hacker News 获取新闻并将链接的标题和 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
最佳答案
在这种情况下,您不应该使用 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
关于ruby - 为什么只获取第一个链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10254339/