What is values_at() in Ruby?

When you display array elements, you can observe that they are presented in the order of their positions. For instance, the first element will always be in the first position, the second element will always be in the second position, and so on.

If you want to display an array with elements in different positions, you can use the values_at() method. The values_at() method in Ruby returns an array with elements placed at specified or given selectors.

Syntax

array.values_at(selector)

Parameters

  • selector: This is the index position of the element to be returned in the array. It can be an integer value or a range.

Return value

The value returned is an array with elements that correspond to the position of the selectors specified.

Code

In the example below, several arrays are created and with the values_at() method we are able to return elements placed at any position that corresponds to their real index position.

# create arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Python", "Ruby", "Java"]
array4 = [true, false, nil, 0, 1]
# use the value_at() method
a = array1.values_at(4) # return elements at index position 4
b = array2.values_at(2, 3) # return elements at index positions 2 and 3
c = array3.values_at(1..2) # return elements within the range of position 1 to 2
d = array4.values_at(2, 3, 1)
# print returned arrays
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"

Free Resources