Hashes in Ruby, Perl and Java
Hashes are lookup tables and also similar to arrays. They are generalization of arrays. Arrays only permit integer indices, example: array[3], but hashes allow any object to be used as "index". So, hash["name"] is allowed. In Ruby, convert arrays to hashes as shown in the link.
As an illustration in Ruby, a ruby Hash is declared with braces. The items to the left of => sign are the keys or index of the Hash, while the items to the right of the => sign are the values of the Hash. So, you can store different values corresponding to each key/index which is quite similar to ruby arrays except for integer indices.
Example:
friend = {
"first name" => "David",
"last name" => "Hilton",
"address" => "34 Main Road",
"city" => "New York",
}
If you pass in one of the keys, the Hash will return the corresponding matching value.
You can store values in a hash just like you would do in an array and similarly, you get value from Hash based on the key passed.
In Java, a list of key/value pairs is called a Java HashMap or HashTable and are present in java.util.* classes. An example is given below:
hashLookup = new HashMap();
hashLookup.put("firsname", "David");
hashLookup.put("lastname", "Hilton");
hashLookup.put("address", "32 Main Road");
hashLookup.put("city", "New York");
In Perl, the perl hashmap would work as follows:
$testHashpMap {$key} = $value;
Note, curly braces {} in the hashmap.
Following example illustrates this:
%testHashpMap = ();
$testHashpMap {"firstname"} = "David";