Basics Of Ruby Hashes

Hashes and arrays are the two basic "aggregate" data types supported by most modern programming languages. The basic interface of a hash is similar to that of an array. The difference is that while an array stores items according to a numeric index, the index of a hash can be any object at all.

empty = Hash.new                            # => {}
empty ={}                                   # => {}
numbers = { 'two' => 2, 'eight' => 8} # => {"two"=>2, "eight"=>8}
numbers = Hash['two', 2, 'eight', 8]        # => {"two"=>2, "eight"=>8}

Once the hash is created, you can do hash lookups and element assignments using the same syntax you would use to view and modify array elements:

numbers["two"]                              # => 2
numbers["ten"] = 10                         # => 10
numbers                                     # => {"two"=>2, "eight"=>8, "ten"=>10}

You can get an array containing the keys or values of a hash with Hash#keys or Hash#values. You can get the entire hash as an array with Hash#to_a:

numbers.keys                                # => ["two", "eight", "ten"]
numbers.values                              # => [2, 8, 10]
numbers.to_a                                 # => [["two", 2], ["eight", 8], ["ten", 10]]

The defining feature of an array is its ordering. Each element of an array is assigned a Fixnum object as its key. The keys start from zero and there can never be gaps. In contrast, a hash has no natural ordering, since its keys can be any objects at all. This feature make hashes useful for storing lightly structured data or key-value pairs.


The main advantage of a hash is that it's often easier to find what you're looking for. Checking whether an array contains a certain value might require scanning the entire array. To see whether a hash contains a value for a certain key, you only need to look up that key. The set library (as seen in the previous chapter) exploits this behavior to implement a class that looks like an array, but has the performance characteristics of a hash.


The downside of using a hash is that since it has no natural ordering, it can't be sorted except by turning it into an array first. There's also no guarantee of order when you iterate over a hash.

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers