Ruby Lesson 3: Arrays and Hashes

Arrays and hashes are indexed collections which are used to store a collection of objects and those stored objects are accessed via a key.

In case of arrays, the key is an integer while in case of hashes, the key is also an object. For example, in case of arrays, we can access the first element by array[0] while in hashes, we can access the element of key first by hash[first].

Array Creation
we can created and initialize array using array literal which is a set of elements between brackets.

Example: a = [1 , ‘Cat’ , 3.14]

In the above example, an array is defined using array literal, and it contains three different objects.

If we are defining an array of strings (words), then Ruby has a better way to do this using %w shortcut

Example: a = %w{cat dog ant}

Array Access
Array elements can be accessed by supplying index of the elements between brackets.

Example: a[1] -> ‘Cat’

Note: If we provided an index of non-existing element, we get nil

Hash Creation
Hashes are similar to arrays, they are created using hash literal. However, hashes are using braces instead of using square brackets.

Example:
inst_section = {
‘cello’ => ‘string’,
‘clarinet’ => ‘woodwind’
}

Note:

  • The left hand side of the => represents the key, while the right hand side represents the value.
  • The keys of the hash should be unique.

Hash Access
In order to access a hash, we use the index key defined in the hash definition.

Example: inst_section[‘cello’]

Note: If we try to access a hash using non-existing key, the returned value will be nil.


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s