Array

Description


ArrayObject represents instance from Array class. An array is a collection of different objects that are ordered and indexed. Elements in an array can belong to any class.

Class Methods


Instance Methods


#

[]

Retrieves an object in an array using Integer index. The index starts from 0. It returns null if the given index is bigger than its size.

 a = [1, 2, 3, "a", "b", "c"]
 a[0]  # => 1
 a[3]  # => "a"
 a[10] # => null

( source )

#

[]=

Assigns value to an array. It requires an index and a value as argument. The array will expand if the assigned index is bigger than its size. Returns the assigned value.

 a = []
 a[0] = 10  # => 10
 a[3] = 20  # => 20
 a          # => [10, null, null, 20]

( source )

#

length

Returns the length of the array.

 [1, 2, 3].length # => 3

( source )

#

pop

Removes the last element in the array and returns it.

 a = [1, 2, 3]
 a.pop # => 3
 a     # => [1, 2]

( source )

#

push

Appends the given object to the array and returns the array.

 a = [1, 2, 3]
 a.push(4) # => [1, 2, 3, 4]

( source )

#

shift

Removes the first element in the array and returns it.

 a = [1, 2, 3]
 a.shift # => 1
 a       # => [2, 3]

( source )

#

each

Loop through each element with the given block.

 a = ["a", "b", "c"]

 a.each do |e|
   puts(e + e)
 end
 # => "aa"
 # => "bb"
 # => "cc"

( source )

#

each_index

( source )

#

map

Loop through each element with the given block. Return a new array with each yield element.

 a = ["a", "b", "c"]

 a.map do |e|
   e + e
 end
 # => ["aa", "bb", "cc"]

( source )

#

select

Loop through each element with the given block. Return a new array with each element that returns true from yield.

 a = [1, 2, 3, 4, 5]

 a.select do |e|
   e + 1 > 3
 end
 # => [3, 4, 5]

( source )

#

at

Retrieves an object in an array using the index argument. It raises an error if index out of range.

 a = [1, 2, 3]
 a.at(0)  # => 1
 a.at(10) # => Error

( source )

#

clear

Removes all elements in the array and returns an empty array.

 a = [1, 2, 3]
 a.clear # => []
 a       # => []

( source )

#

concat

Appends any number of argument to the array.

 a = [1, 2, 3]
 a.concat(4, 5, 6)
 a # => [1, 2, 3, 4, 5, 6]

( source )

#

count

Loop through each element with the given block. Return the sum of elements that return true from yield.

 a = [1, 2, 3, 4, 5]

 a.count do |e|
   e * 2 > 3
 end
 # => 4

( source )

#

rotate

Returns a new array by putting the desired element as the first element. Use integer index as an argument to retrieve the element.

 a = ["a", "b", "c", "d"]

 a.rotate    # => ["b", "c", "d", "a"]
 a.rotate(2) # => ["c", "d", "a", "b"]
 a.rotate(3) # => ["d", "a", "b", "c"]

( source )

#

first

Returns the first element of the array.

( source )

#

last

Returns the last element of the array.

( source )