Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
array
communitycreator

What is values_at() in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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}"

RELATED TAGS

ruby
array
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring