Ruby Operators and Arrays - Hashes
(Page 3 of 4 )
If you want to work with words instead of numbers for you indices, hashes is the way to go. Let's say you want to make a list of people's weight and print out a person from the list at random, to humiliate them throughout the day. For this, we could use Hashes, which remind me of hash browns and make me very hungry.
Hashes are also referred to as associative arrays. And unlike arrays that use [] brackets, hashes use the curly braces {}.
employees_weight = {"James" = "400", "Chuck" = "250"}
Instead of index numbers, in Hashes we use hash keys. In the above instance, James is a hash key and 400 is the value you associate with that key. So let's say I want to embarrass that fatty James (I'm said fatty by the way), we would use the following code, then call everyone over to look at it, making sure to point and slap the cheeseburger out of his (my) hand.
employees_weight = {"James" = "400", "Chuck" = "250"}
puts "James weighs so much we have to put it on a line by itself:"
puts employees_weight["James"]
As you can see, to access the data in the hash, we used the [ ]. Why this is, I don't know. The result:
James weighs so much we have to put it on a line by itself:
400
Next: Home on the Range >>
More Ruby-on-Rails Articles
More By James Payne