2013-05-12 109 views
1

我正在執行一個屏幕抓取以獲得足球結果,並將得分作爲一個字符串,例如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 
+0

該方法是否完整?似乎你失去了一個'結局'。 – 2013-05-12 13:33:22

回答

2

無需爲每個。這樣做:

home_score, away_score = score.split("-").map(&:to_i) 
+0

驚人的作品..爲什麼沒有這個例子,如果你不介意解釋請 – Richlewis 2013-05-12 13:35:54

+0

正如你發現,在1.9沒有每個字符串。有each_char像每個(pre 1.9)一樣起作用,並會穿過目標字符串中的字符。你可以編寫一個例程,通過在破折號之前保存字符來實現你想要的功能,以及破折號之後的字符到away_score,但是split可以很好地(神奇地?)爲你做到這一點。 – seph 2013-05-12 13:44:47

+0

再次感謝您的幫助,非常感謝 – Richlewis 2013-05-12 13:51:42

相關問題