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.
array.values_at(selector)
selector
: This is the index position of the element to be returned in the array. It can be an integer value or a range.The value returned is an array with elements that correspond to the position of the selectors specified.
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 arraysarray1 = [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() methoda = array1.values_at(4) # return elements at index position 4b = array2.values_at(2, 3) # return elements at index positions 2 and 3c = array3.values_at(1..2) # return elements within the range of position 1 to 2d = array4.values_at(2, 3, 1)# print returned arraysputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"