我有一个循环输出我从网站上获取的信息。为了使信息以可读的方式显示,我将它插入到一个数组中,该数组将显示在我的视图页面上。但是,该数组不会存储所有检索到的值,而是仅保存附加到它的最后一个值。最后我只能得到插入要显示的数组的最后一个值。
我的控制器文件...
def home
scrape()
end
private
def scrape
require 'rubygems'
require 'nokogiri'
require 'open-uri'
time = Time.new
month = I18n.t("date.abbr_month_names")[time.month]
day = time.day
@strings = []
#United States
cities = [
"sfbay", "losangeles", "athensga", "phoenix", "santabarbara", "denver",
"panamacity", "miami", "austin", "bakersfield", "keys", "newyork"
]
cities.map do |city|
#Search Terms
search_terms = ["mechanic", "car", "tech"]
search_terms.map do |term|
escaped_term = CGI.escape(term)
url = "http://#{city}.craigslist.org/search/jjj?query=#{escaped_term}&catAbb=jjj&
srchType=A"
doc = Nokogiri::HTML(open(url))
doc.css(".row").map do |row|
date = row.css(".itemdate").text
a_tag = row.css("a")[0]
text = a_tag.text
link = a_tag[:href]
@strings == []
if date = "#{month} #{day}"
@strings << "#{date} #{text} #{link}"
end
end
end
end
end
在视图 home.html.erb 文件中...
<%= raw(@strings.join('<br />')) %>
因此,当我转到主页时,我只显示插入数组的最后一个值。出了什么问题,我该如何解决?