Chapter 3.5 Arrays

An array is an integer indexed and ordered collection of elements. Ruby’s implementation of the array is slightly different. Elements of the Ruby array do not have to be of the same type. Specify the type of the array before it is initialized for use.

You can initialize an array with values of any type, variables, values returned from methods, literals or quoted strings, or an empty array.

To add an element to the end of an array, use the << operator, the push method, or the insert method.

Example:

example_array.push(23, 24)
--> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 24]

example_array.insert(-1, 25)
--> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 25]

example_array << 12
--> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]

The method push permits you to push one or more elements onto the end of an array. The insert method permits you to insert elements at a specified index. The << operator permits you to push specified elements on to the end of an existing array.

To use an array element’s value, reference the desired element by index in the form array_name[index].

puts example_array[0]
--> 1

index =  3

example_array[index]
--> 4

example_array[0..3]
--> [1, 2, 3, 4]

The at method also references array elements.

puts example_array.at(0)
--> 1

The fetch method can specify a default value to return if the specified index is not found.

puts example_array.fetch(53, "Error!")
--> Error!

The values_at method operates like at, fetch, and the [] operator. This method, however, takes a number of indexes to fetch and return as an array.

puts example_array.values_at(0, 1, 2)
--> [1, 2, 3]

The pop method grabs the last element in the array and removes it from the array.

example_array.pop
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]

The shift method grabs the first element from the array and removes it shifting all other elements back one index.

example_array.shift
--> [2, 3, 4, 5, 6, 7, 8, 9, 10]

The delete_at method deletes the element at the index specified as a parameter and returns the value of that element.

puts example_array.delete_at(2)
--> 3

example_array
--> [1, 2, 4, 5, 6, 7, 8, 9, 10]

The delete method deletes and returns the value that is referenced as a parameter rather than the index.

puts example_array.delete(3)
--> 3

example_array
--> [1, 2, 4, 5, 6, 7, 8, 9, 10]

puts example_array.delete(500) { "Error" }
--> Error

  • Currently 2.97/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 0 comments