Arrays in Ruby

The Array class is a built-it Ruby object instances of which (arrays) are used as ordered and indexed lists of Ruby objects.

Commonly arrays in Ruby are created using literal constructors.

my_array = [1, 2, "three"]

The :[] method is used to access elements of an array.

captains = ["Kirk", "Picard", "Hook"]
captains.send(:[], 0) # => "Kirk"
captains[0] # => "Kirk"
captains[-1] # => "Hook"

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2..4] # => ["c", "d", "e"]
letters.first # => "a"
letters.last # => "e"
letters.take(3) # => ["a", "b", "c"]

Other common methods that come with Ruby arrays are empty?, any?, all?, none?, one?, count, size, length, include?, push, shift, unshift, insert, pop, delete_at, delete, compact, uniq, select, reject, flatten, shuffle, slice, sort.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.