CHAPTER 4

image

Arrays

Ruby arrays are integer–indexed arrays starting at position 0, rather like Java or C. Negative values can be used to retrieve values from the array from the end, so −1 would show the last element of an array, and −2 would show the second from last element.

2.1.0 :001 > array = [1,10,3,1] => [1, 10, 3, 1]2.1.0 :002 > array[0] => 12.1.0 :003 > array[-1] => 12.1.0 :004 > array[-2] => 3

Creating Arrays

An array can be created within ruby in a number of different syntaxes, the simplest is the use of the literal constructor []. Arrays are not type dependent, and therefore can contain multiple data types such as another array, a string ...

Get Ruby Quick Syntax Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.