O'Reilly logo

Ruby in a Nutshell by Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Array — Array class

Synopsis

Array is a class for an ordered collection of objects, indexed by integer. Any kind of object may be stored in an Array. Arrays grow as you add elements.

Included Module

Enumerable

Class Methods

Array[x...]

Creates an array.

Array::new([size=0[, fill=nil]])

Creates an array. Its size and initial values may also be specified.

Array::new(4, "foo")      # => ["foo","foo","foo","foo"]

Instance Methods

Methods of the Array class ending in ! modify their receiver and return an array if modification took place, otherwise nil. Methods without a ! return a modified copy of the array.

arr & array

Returns an array of elements common to both arrays.

[1,3,5]|[1,2,3]           # => [1,3]
[1,3,5]|[2,4,6]           # => [1,2,3,4,5,6]
arr| array

Returns an array combining elements from both arrays.

[1,3,5]|[2,4,6]           # => [1,2,3,4,5,6]
arr * n

If n is an integer, returns a copy of array with n copies of arr concatenated to it. If n is a string, the equivalent of arr.join(n) is performed.

[5] * 3                   # => [5, 5, 5].
["foo", "bar"] * "-"      # => "foo-bar"
arr + array

Returns a copy of arr with array concatenated to its end.

arr - array

Returns a new array that is a copy of arr, removing any items in array.

[1, 2, 3, 4] - [2, 3]     # => [1, 4]
arr << item

Appends item to arr.

arr[n]

References the nth element of arr. If n is negative, it’s interpreted as an offset from the end of arr.

arr[n..m]
arr[n,len]

Returns a partial string.

arr[n]=item
arr[r..m]=array
arr[r,len]=array

Assigns item or arr to the specified elements.

arr = [0, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required