1

I am trying this for the first time and am not sure I have quite achieved what i want to. I am pulling in data via a screen scrape as arrays and want to put them into a hash.

I have a model with columns :home_team and :away_team and would like to post the data captured via the screen scrape to these

I was hoping someone could quickly run this in a rb file

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

and advise if this is actually a hash as it seems to be an array as i cant see the hash name being outputted. i would of expected something like this

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

any help appreciated

0

2 Answers 2

2

You actually get a Hash back. But it looks different from the one you expected. You expect a Hash inside a Hash.

Some examples to clarify:

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

The "Hash name" as you call it, is never "outputed". A Hash is basically a Array with a different index. To clarify this a bit:

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

Basically with a Hash you additionally define, how and where to find the values by defining the key explicitly, while an array always stores it with a numerical index.

Sign up to request clarification or add additional context in comments.

Comments

1

here is the solution

team_clean = Hash[:team_clean => [Hash[:home_team => home_team,:away_team => away_team]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.