Main Content

Collection objects (array and hash) in Ruby

Archive - Originally posted on "The Horse's Mouth" - 2009-07-16 05:31:07 - Graham Ellis

Ruby has two collection objects - Arrays (where you access elements based on their numeric position) and hashes (where you can access elements based on a key, rarely numeric). That's similar in all but name to many other languages, although the names may be different (arrays or lists; hashes or dictionaries or associative arrays!). We covered many of the basics on yesterday's learning to program in Ruby course - and here are the sample programs I wrote as an illustration during the Arrays and Hashes section:

[link] Arrays, and iterating through them

[link] Array methods such as grep

[link] Simulated table (an array of arrays)

[link] Set up a hash and use it

[link] Simple but practical hash example

[link] Count the number of visits from each IP address (Includes how to sort a hash - or rather the keys - based on the values the hash contains in Ruby)