サッカーの結果を取得するためにスクリーン グラブを実行していますが、スコアは 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 が指摘したように、 each は必要ありませんでした。それが他の誰かに役立つ場合、私の最終的なタスクは次のようになります
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