Array仅将最后一个值保存在rails上的ruby中

时间:2012-11-27 01:22:31

标签: ruby-on-rails ruby arrays ruby-on-rails-3 nokogiri

我有一个循环,输出我从网站抓取的信息。为了使信息以可读的方式显示,我将其插入到将在我的视图页面上显示的数组中。但是,该数组不会存储检索到的所有值,而只会保存附加到它的最后一个值。最后,我只能将最后一个值插入要显示的数组中。

我的控制器文件......

def home
  scrap()
end

private

def scrap 

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 />')) %>

所以当我进入主页时,我只显示插入数组的最后一个值。有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:1)

首先,您为每个城市的每一行创建一个新数组。 (但实际上不是;分配是比较,==,此刻。)

对于另一个,您将日期设置为“#{month}#{day}”,而不是进行比较。