Variables

Arrays in Ruby

An array is a variable that holds multiple values, indicated by an index. Ruby arrays can contain mixed types.


Syntax
#declaring and assigning an array
array = [value1, value2, ...]

#appending to an array
array << value

#declaring an empty array
array = Array.new(size)

Notes

An index out of bounds returns a value of null.

The array index range is from 0 to size minus 1. Negative indices start at the end of the array and work backwards.

An array can be dynamically sized. If an item is written to an array index outside the range, all previous indices are assigned a value of null (if no value was previously assigned).


Example
cities = ["Toronto", "San Francisco", "Seattle"]

>> cities[0]
=> "Toronto"

#index out of bounds
>> cities[3]
=> nil



See Also
Documentation

Class: Array - Ruby Docs

Add to Slack

< Constants   |   Symbols >

© 2018 SyntaxDB. All Rights Reserved.