1

我正在执行屏幕抓取以获取足球结果,并且分数以字符串形式出现,例如 2-2。理想情况下,我希望将该分数分成 home_score 和 away_score,然后将每个结果保存到我的模型中

目前我这样做

def get_results # Get me all results
 doc = Nokogiri::HTML(open(RESULTS_URL))
 days = doc.css('.table-header').each do |h2_tag|
 date = Date.parse(h2_tag.text.strip).to_date
  matches = h2_tag.xpath('following-sibling::*[1]').css('tr.report')
  matches.each do |match|
   home_team = match.css('.team-home').text.strip
   away_team = match.css('.team-away').text.strip
   score = match.css('.score').text.strip
    Result.create!(home_team: home_team, away_team: away_team, score: score, fixture_date: date)
  end
 end

从进一步阅读中我可以看到您可以使用 .split 方法

 .split("x").map(&:to_i)

我能做到吗

score.each do |s|
home_score, away_score = s.split("-").map(&:to_i)
Result.create!(home_score: home_score, away_score: away_score)
end

但是如何整合到我当前的设置中是什么让我感到困惑,即使我的逻辑是正确的,我仍然希望将 home_score 和 away_score 分配给正确的结果

提前感谢您的帮助

编辑

好的,到目前为止答案是否定的,我不能这样做,在运行 rake 任务后我得到一个错误

undefined method `each' for "1-2":String

.each 不起作用的原因是因为 each 是 ruby​​ 1.8 中的 String 方法,并且在 Ruby 1.9 中被删除。我已经尝试过 each_char,它现在保存了一些结果而不是其他结果,并且当它保存时 home_score 和 away_score 没有正确分配

回答

正如@seph 指出的那样,每个都不需要,如果它对其他人有帮助,我的最终任务看起来像这样

def get_results # Get me all results
  doc = Nokogiri::HTML(open(RESULTS_URL))
  days = doc.css('.table-header').each do |h2_tag|
  date = Date.parse(h2_tag.text.strip).to_date
  matches = h2_tag.xpath('following-sibling::*[1]').css('tr.report')
    matches.each do |match|
     home_team = match.css('.team-home').text.strip
     away_team = match.css('.team-away').text.strip
     score = match.css('.score').text.strip
     home_score, away_score = score.split("-").map(&:to_i)
     Result.create!(home_team: home_team, away_team: away_team, fixture_date: date, home_score: home_score, away_score: away_score)

    end
   end
  end
4

1 回答 1

2

不需要每个。做这个:

home_score, away_score = score.split("-").map(&:to_i)
于 2013-05-12T13:32:36.327 回答