1

我是第一次尝试这个,我不确定我是否已经完全实现了我想要的。我通过屏幕抓取将数据作为数组提取,并希望将它们放入哈希中。

我有一个带有 :home_team 和 :away_team 列的模型,并且想将通过屏幕抓取捕获的数据发布到这些

我希望有人可以在 rb 文件中快速运行它

require 'open-uri'
require 'nokogiri'

FIXTURE_URL = "http://www.bbc.co.uk/sport/football/premier-league/fixtures"

doc = Nokogiri::HTML(open(FIXTURE_URL))
home_team = doc.css(".team-home.teams").map {|team| team.text.strip}
away_team = doc.css(".team-away.teams").map {|team| team.text.strip}
team_clean = Hash[:home_team => home_team, :away_team => away_team]
puts team_clean.inspect

并建议这是否实际上是一个哈希,因为它似乎是一个数组,因为我看不到正在输出的哈希名称。我会期待这样的事情

{"team_clean"=>[{:home_team => "Man Utd", "Chelsea", "Liverpool"}, 
          {:away_team => "Swansea", "Cardiff"}]}

任何帮助表示赞赏

4

2 回答 2

2

你实际上得到了一个哈希值。但它看起来和你想象的不一样。您期望哈希中的哈希。

一些例子来澄清:

hash = {}
hash.class
 => Hash 

hash = { home_team: [], away_team: [] }
hash.class
=> Hash
hash[:home_team].class
=> Array

hash = { hash: { home_team: [], away_team: [] } }  
hash.class
=> Hash
hash[:hash].class
=> Hash
hash[:hash][:home_team].class
=> Array

您所说的“哈希名称”永远不会“输出”。哈希基本上是具有不同索引的数组。为了澄清这一点:

hash = { 0 => "A", 1 => "B" }
array = ["A", "B"]
hash[0]
=> "A"
array[0]
=> "A"
hash[1]
=> "B"
array[1]
=> "B"

基本上,您还可以使用 Hash 来定义如何以及在何处通过显式定义键来查找值,而数组始终使用数字索引存储它。

于 2013-03-14T09:30:45.743 回答
1

这是解决方案

team_clean = Hash[:team_clean => [Hash[:home_team => home_team,:away_team => away_team]]]
于 2013-03-14T09:32:29.860 回答