Home »
Ruby Tutorial
Ruby Array.select Method
By IncludeHelp Last updated : November 28, 2024
In the last articles, we have seen how to iterate over the instances of Array class? We have seen that we have got methods like Array.each, Array.reverse_each and Array.map for this purpose. In this article, we will learn about the implementation of Array.select.
Description and Usage
Array.select method, as the name suggests, is used to select some elements from the Array. This method is non-destructive and does not bring any change in the actual values of the Array object. This method works based on certain conditions which you will provide inside the pair of parentheses. This method is based on the criteria you provide inside the block. This method will not work if you do not specify any conditions inside the block. Though it will not throw an exception you will get nil as the result. So, if you are working with this method you should be having certain conditions based on which the element is going to be selected from the object of Array class. If you want to print all the elements of Array instance then you can go for Array.each method and avoid going for this one.
Syntax
Array.select{|var| #condition}
Parameters
This method does not permit the passing of any arguments instead it mandates a condition.
Example 1
=begin
Ruby program to demonstrate Array.select
=end
# array declaration
num = [2,44,2,5,7,83,5,67,12,11,90,78,9]
puts "Enter 'a' for Even numbers and 'b' for odd numbers"
opt = gets.chomp
if opt == 'a'
puts "Even numbers are:"
puts num.select{|num|
num%2 == 0
}
elsif opt == 'b'
puts "Odd numbers are:"
puts num.select{|num|
num%2 !=0
}
else
puts "Wrong selection. Input valid option"
end
Output
RUN 1:
Enter 'a' for Even numbers and 'b' for odd numbers
a
Even numbers are:
2
44
2
12
90
78
RUN 2:
Enter 'a' for Even numbers and 'b' for odd numbers
b
Odd numbers are:
5
7
83
5
67
11
9
Explanation
In the above code, you can observe that we are taking input from the user about what type of numbers the user wants as the output. This is because we want to pass certain conditions inside the Array.select method. We are giving the response to the user as per the option provided by the user and this method is used in this way only.
Example 2
=begin
Ruby program to demonstrate Array.select
=end
# array declaration
num = [2,44,2,5,7,83,5,67,12,11,90,78,9]
puts num.select{|a|}
Output
# no o/p
Explanation
In the above output, you can observe that when you are not specifying any condition inside the method, then you are not getting anything as the output.