我是第一次尝试这个,我不确定我是否已经达到了我想要的目标。我通过屏幕刮取数据作为数组,并希望将它们放入哈希值。
我有一个带有列的模型: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"}]}
任何帮助表示赞赏
答案 0 :(得分:2)
你真的得到了哈希。但它看起来与你预期的不同。你希望Hash里面有哈希。
澄清一些例子:
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,您还可以通过显式定义键来定义,查找值的方式和位置,而数组始终使用数字索引存储它。
答案 1 :(得分:1)
这是解决方案
team_clean = Hash[:team_clean => [Hash[:home_team => home_team,:away_team => away_team]]]