将一个字符串拆分为两个独立的属性ruby

时间:2013-05-12 13:10:22

标签: ruby ruby-on-rails-3 model split

我正在执行屏幕抓取以获得足球结果,并且分数以字符串形式出现,例如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不起作用是因为每个都是ruby 1.8中String的一个方法,它在Ruby 1.9中删除了。我已经尝试过each_char,它现在可以保存一些结果而不是其他结果,当它确实保存了home_score并且off_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

1 个答案:

答案 0 :(得分:2)

不需要每一个。这样做:

home_score, away_score = score.split("-").map(&:to_i)
相关问题