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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.