我正在执行一个屏幕抓取以获得足球结果,并将得分作为一个字符串,例如2-2。我会非常想有是有成绩分成home_score然后away_score其保存到我的模型为每个结果将字符串拆分为两个单独的属性ruby
目前我做这
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
的原因。每个不工作是因为每一个为字符串的方法在RU到1.8,它在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
该方法是否完整?似乎你失去了一个'结局'。 – 2013-05-12 13:33:22