Ruby Language Arrays Accessing elements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can access the elements of an array by their indices. Array index numbering starts at 0.

%w(a b c)[0] # => 'a'
%w(a b c)[1] # => 'b'

You can crop an array using range

%w(a b c d)[1..2] # => ['b', 'c'] (indices from 1 to 2, including the 2)
%w(a b c d)[1...2] # => ['b'] (indices from 1 to 2, excluding the 2)

This returns a new array, but doesn't affect the original. Ruby also supports the use of negative indices.

%w(a b c)[-1] # => 'c'
%w(a b c)[-2] # => 'b'

You can combine negative and positive indices as well

%w(a b c d e)[1...-1] # => ['b', 'c', 'd']

Other useful methods

Use first to access the first element in an array:

[1, 2, 3, 4].first # => 1

Or first(n) to access the first n elements returned in an array:

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

Similarly for last and last(n):

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

Use sample to access a random element in a array:

[1, 2, 3, 4].sample  # => 3
[1, 2, 3, 4].sample  # => 1

Or sample(n):

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


Got any Ruby Language Question?