Reputation: 15394
I am performing a screen grab to get football results and the score comes as a string, 2-2 for example. What I would ideally like to have is have that score split into home_score and away_score which is then saved into my model for each result
At the moment i do this
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
From some further reading i can see that you can use the .split method
.split("x").map(&:to_i)
so would i be able to do this
score.each do |s|
home_score, away_score = s.split("-").map(&:to_i)
Result.create!(home_score: home_score, away_score: away_score)
end
but how to integrate into my current setup is whats throwing me and thats even if my logic is correct, I still want the home_score and away_score to be assigned to the correct result
Thanks in advance for any help
EDIT
Ok so far the answer is no i cannot do it this way, after running the rake task I get an error
undefined method `each' for "1-2":String
The reason .each doesnt work is because each was a method of String in ruby 1.8 and it was removed in Ruby 1.9. i have tried each_char, which now saves some results and not others and when it does save home_score and away_score are not assigned correctly
Answer
As @seph pointed out the each was not needed, if it helps anyone else my final task looks like this
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
Upvotes: 1
Views: 162
Reputation: 6076
No need for the each. Do this:
home_score, away_score = score.split("-").map(&:to_i)
Upvotes: 2