Looping through an array of hashes? help

Hello, I’ve been toying with general functionality using the below. This
is a sample of what im trying to do.

I create an array of hashes and then try to loop through each array by
index and then go to a link by a key.

by itself this works perfect but when looping through the array its
problematic.
$testDailies[x][“Link”]

This works the first time then gives a type error calling my variable
for the index location a STRING not an int.

I’ve tried alot of different ways including to_i and using the |i| in
the each loop rather than my own incremented int variable.

I’m new any ideas?

require “rubygems”
require “watir”

x = 0
createDailyHash()
$ie = Watir::IE.new

$testDailies.each{ |i|
$ie.goto $testDailies[x][“Link”]
x = x + 1
}

def createDailyHash()

$testDailies = Array.new

$testDailies[0] = {“Name” => “jelly”, “Link” =>
http://www.google.com”, “ID” => “0”}
$testDailies[1] = {“Name” => “omelette”, “Link” =>
http://www.google.com”, “ID” => “1”},
$testDailies[2] = {“Name” => “giveaway”, “Link” =>
http://www.google.com”, “ID” => “2”},
$testDailies[3] = {“Name” => “bankInterest”, “Link” =>
http://www.google.com”, “ID” => “3”},
$testDailies[4] = {“Name” => “shopOfOffers”, “Link” =>
http://www.google.com”, “ID” => “4”},
$testDailies[5] = {“Name” => “petPark”, “Link” =>
http://www.google.com”, “ID” => “5”},
$testDailies[6] = {“Name” => “freebies”, “Link” =>
http://www.google.com”, “ID” => “6”},
$testDailies[7] = {“Name” => “obsidian”, “Link” =>
http://www.google.com”, “ID” => “7”},
$testDailies[8] = {“Name” => “appleBobbing”, “Link” =>
http://www.google.com”, “ID” => “8”},
$testDailies[9] = {“Name” => “anchor”, “Link” =>
http://www.google.com”, “ID” => “9”},
$testDailies[10] = {“Name” => “advert”, “Link” =>
http://www.google.com”, “ID” => “10”},
$testDailies[11] = {“Name” => “tombola”, “Link” =>
http://www.google.com”, “ID” => “11”},
$testDailies[12] = {“Name” => “nowager”, “Link” =>
http://www.google.com”, “ID” => “12”},
$testDailies[13] = {“Name” => “fruitMachine”, “Link” =>
http://www.google.com”, “ID” => “13”},
$testDailies[14] = {“Name” => “coltazan”, “Link” =>
http://www.google.com”, “ID” => “14”},
$testDailies[15] = {“Name” => “tdmbgpop”, “Link” =>
http://www.google.com”, “ID” => “15”
end

On Tue, Jan 3, 2012 at 4:00 PM, Shawn M. [email protected] wrote:

$ie.goto $testDailies[x][“Link”]
x = x + 1
}

The each { |i| there doesn’t give you an index like you’re expecting.
Instead, it gives you an object. Because of this, you don’t need an i or
an
x there. You just need a variable to receive the hash.

I cleaned your example up into a bit more idiomatic Ruby:

Just for fun, here’s a version that stores the array of data you’re
populating at the end of the script as a YAML file :wink:

Err whoops, here’s a version without the Water::IE duck type class I
made :slight_smile:

Perfect, thank you for the response. It does exactly what i was looking
for. Also thanks for adding the YAML example.