Information Technology Reference
In-Depth Information
The first element is also accessible via the convenient first method.
To complement the first method, Ruby also exposes a last method.
Sp ecifying a range inside the brackets will slice the array from the first index up to and
including the second index.
For example, you could use Ruby arrays to store an ordered list of all employees in the
order in which they were hired. Each time a new employee joins the team, he is added to
the list. The first employee is at index 0 , the second employee is at index 1 , and so on:
employees [ 0 ] #=> Chase
employees [ 1 ] #=> Jake
When a new employee joins the team, his name is pushed onto the end of the array:
employees << 'Bob'
employees . last #=> Bob
Hashes
Ruby also supports hashes (sometimes called dictionaries or maps in other languages).
Hashes are key-value pairs that behave similarly to arrays. Hashes are created using liter-
al curly braces ( {} ):
prices = { oscar : 4 . 55 , boars : 5 . 23 , wright : 4 . 65 , beelers : 6 . 99 }
prices [ :oscar ] #=> 4.55
prices [ :boars ] #=> 5.23
prices [ :oscar ] = 1 . 00
prices . values #=> [4.55, 5.23, 4.65, 6.99]
In dividual elements are accessed using the bracket notation, much like arrays.
Th e same bracket notation can be used to set elements at a particular key.
Ha shes respond to helpful methods like keys and values .
 
 
 
 
Search WWH ::




Custom Search