Home » Ruby programming

Array.values_at() Method with Example in Ruby

Ruby Array.values_at() Method: Here, we are going to learn about the Array.values_at() Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 15, 2020

Array.values_at() Method

In this article, we will study about Array.values_at() Method. You all must be thinking the method must be doing something which is related to finding values from the Array instance. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.

Method description:

This method is a public instance method and defined for the Array class in Ruby's library. This method works in a way that it returns an Array instance that contains the object in self corresponding to the given selector. Here selectors refer to the indices you provide to the method at the time of its invocation. These selectors can be either indices or ranges.

Syntax:

    array_instance.values_at(objects,...) -> array

Argument(s) required:

This method can take n number of objects. You can even provide ranges as the argument.

Example 1:

=begin
  Ruby program to demonstrate values_at method
=end

# array declaration
table = [2,4,8,10,12,134,160,180,200,344]

puts "Array values_at implementation"

puts "Enter the number of indices you want to enter:"
num = gets.chomp.to_i

for i in 1..num
	puts "Enter the index:"
	ele = gets.chomp.to_i
	puts "The value at #{ele} is #{table.values_at(ele)}"
end

Output

Array values_at implementation
Enter the number of indices you want to enter:
 2
Enter the index:
 0
The value at 0 is [2]
Enter the index:
 1
The value at 1 is [4]

Explanation:

In the above code, you can observe that we are fetching values from the Array instance with the help of the Array.values_at() method. The method is a returning element whose corresponding index is provided by the user. This method returns an Array that is why a single object is also coming inside the square braces.

Example 2:

=begin
  Ruby program to demonstrate values_at method
=end

# array declaration
table = [2,4,8,10,12,134,160,180,200,344]

puts "Array values_at implementation"

puts "Enter the lower limit:"
lwr = gets.chomp.to_i
puts "Enter the upper limit:"
upr = gets.chomp.to_i

puts "The objects which lie in the range are : #{table.values_at(lwr..upr)}"

Output

Array values_at implementation
Enter the lower limit:
 2
Enter the upper limit:
 5
The objects which lie in the range are : [8, 10, 12, 134]

Explanation:

In the above code, you can observe that we have asked the user for upper and lower limits so that we can pass that range inside the method. In the output, you can see that the Array which is returned by the method is having all the objects which lie in that range.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.