Question

I'm trying to fetch news from Hacker News and write a link's title and URL to an HTML file. However, only the first link is getting written and others are not. What am I doing wrong?

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
Était-ce utile?

La solution

You shouldn't use return keyword in this case. It ends the method prematurely and returns only the first link. Use this instead:

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top