Home »
Ruby Tutorial
Ruby Array.permutation() Method
By IncludeHelp Last updated : November 28, 2024
In this article, we will study about Array.permutation() method. You all must be thinking the method must be doing something related to creating permutations of certain elements. 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.
Description and Usage
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 will take elements from the Array instance and make permutations according to the number passed in the method and then it returns the Array instance itself. This method does not guarantee the order of the elements yielded. This method is invoked with a block or an Array and the result is being converted into the Array instance with the help of .to_a method.
If you do not provide any block then the enumerator is returned itself.
Syntax
permutation(n) { |c| block }
Parameters
This method only requires one argument. This argument decides the number of permutations possible from the elements of Array instance.
Example 1
=begin
Ruby program to demonstrate permutation method
=end
a = [1, 2, 3]
puts "Array permutation method"
print a.permutation(1).to_a
puts ""
print a.permutation(2).to_a
puts ""
print a.permutation(3).to_a
Output
Array permutation method
[[1], [2], [3]]
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation
In the above code, you can observe that this method is used to create permutations of the array elements. Permutations are being created based on the argument passed inside the method. N number of combinations can be made and that n can be the multiplication of length of Array instance multiplied by the integer passed in the method.
Example 2
=begin
Ruby program to demonstrate permutation method
=end
a = ["Sucharu","Shalini"]
puts "Array permutation method"
print a.permutation(1).to_a
puts ""
print a.permutation(2).to_a
puts ""
print a.permutation(3).to_a
Output
Array permutation method
[["Sucharu"], ["Shalini"]]
[["Sucharu", "Shalini"], ["Shalini", "Sucharu"]]
[]
Explanation
In the above example, you can observe that this method works upon String Array instances as well. This method is returning elements after making their permutations. In the case of String Array, the method will return "nil" or you can say that permutation is not possible if the length of the Array is lesser than the integer argument passed in the method at the time of invocation.