Skip to content

Ruby Array API

Ruby's Array — an ordered, integer-indexed collection of any objects, with rich functional methods.

1 class · 8 methods

Array

8 methods

Arrays are ordered, integer-indexed collections of any object.

Array#push(*objects) -> Array

Appends each given object to self. Returns self (with aliases <<).

Parameters

NameTypeDescription
objectsObjectObjects to append.

Returns

Array

Example

ruby
a = [1, 2]
a.push(3)
a.push(4, 5)
# a == [1, 2, 3, 4, 5]
a << 6
# a == [1, 2, 3, 4, 5, 6]
Array#pop -> object | nil

Removes and returns the last element of self, or nil if the array is empty.

Returns

Object | nil

Example

ruby
a = [1, 2, 3]
x = a.pop  # 3
# a == [1, 2]
Array#length -> Integer

Returns the number of elements in self. Alias: size.

Returns

Integer

Example

ruby
[1, 2, 3].length  # 3
[].size           # 0
Array#each {|item| block} -> Array

Calls the given block once for each element in self, passing that element as a parameter.

Returns

Array

Example

ruby
[1, 2, 3].each { |x| puts x }
# prints:
# 1
# 2
# 3
Array#map {|item| block} -> Array

Returns a new array containing the values returned by the block for each element. Alias: collect.

Returns

Array

Example

ruby
[1, 2, 3].map { |x| x * x }  # [1, 4, 9]
Array#select {|item| block} -> Array

Returns a new array containing all elements for which the block returns a truthy value.

Returns

Array

Example

ruby
[1, 2, 3, 4].select { |x| x.even? }  # [2, 4]
Array#include?(object) -> bool

Returns true if the given object is present in self, false otherwise.

Parameters

NameTypeDescription
objectObjectObject to check for.

Returns

Boolean

Example

ruby
[1, 2, 3].include?(2)  # true
[1, 2, 3].include?(9)  # false
Array#join(separator=$,) -> String

Returns the concatenation of all elements converted to strings, joined by separator.

Parameters

NameTypeDescription
separatorStringSeparator between elements (default empty).

Returns

String

Example

ruby
["a", "b", "c"].join("-")  # "a-b-c"
[1, 2, 3].join(", ")      # "1, 2, 3"