Difference between revisions of "Help:TT Hashes"
HELP PAGE DISCUSSION CLOSE
m
 
m (1 revision)
 
(No difference)

Latest revision as of 23:21, 24 March 2013

Storing and retrieving data from hashes

Hashes, also known as associative arrays, resemble arrays in that they both are designed to hold a group of data. While arrays arrange the data in a specific order, hashes store values with a key associated with each of them. Arrays can be thought of as hashes in that the cells hold the values while the keys are basically the array index numbers. Let's look at a hash example to get an idea of how they are defined.

[% filecabinet = { 'a2i' => 35, 'j2r' => 42, 's2z' => 28, }; "File cabinet has ${filecabinet.size} folders.\n"; "Folder \"a2i\" has ${filecabinet.a2i} files.\n"; "Folder \"j2r\" has ${filecabinet.j2r} files.\n"; "Folder \"s2z\" has ${filecabinet.s2z} files.\n"; %]

The example above will result in the output below:

File cabinet has 3 folders. Folder "a2i" has 35 files. Folder "j2r" has 42 files. Folder "s2z" has 28 files.

The code above creates a hash array called filecabinet, stores information into the hash, then finally accesses the contents of the hash. The hash is defined using braces {}. Inside the braces {}, a series of keys and values are defined. A key of a hash is basically an index in a hash, used to access the value that corresponds to the key. So in our example, the value of 35 is assigned to the key 'a2i'. Values in a hash can be numbers, strings, arrays or even hashes. The value is assigned to the key with the => symbol, and each key/value pairs are separated by commas.


To access the values from a hash, you follow the format arrayname.key. So to retrieve the value assigned to the key 'j2r', simply use filecabinet.j2r. Accessing a hash is very similar to reading from an array, except you specify the key instead of an index. You can also find out the number of key/value pairs in a hash with the size function. The example above prints out the number of key/value pairs or the number folders in the hash filecabinet, then prints out all the folder labels and the number of files in each folder.


Back to Table of Contents