Ruby permutation array method

In ruby programming language, the permutation() array method is used to obtain all permutations. Syntax of this method as follows.

permutation → Enumerator
permutation(n) → Enumerator
permutation(n) {|v| block} → return array
permutation {|v| block} → return array

This method can be basically return two types of values. Such as Enumerator and new array which contains resultant permutable element. This method can take one parameter value, That is indicate the length of permutation result.

Enumerator occurs when method are not include block. In other case method is returning a new array which inner array contains resultant element.

Ruby permutation method example

In this section are given basic example to understand how to use this method. Such as how to use this method in special cases etc. Let's see an example which is based on Enumerator.

# Our array
record  = ['a','b','c']

# Return Enumerator
task1 = record.permutation    # When no parameter
task2 = record.permutation(2) # Size 2

# Convert Enumerator to array
t1 = task1.to_a
t2 = task2.to_a

# Display result
print("record : ", record)
print("\nt1 : ", t1)
print("\nt2 : ", t2)
Ruby permutation method example 1
record : ["a", "b", "c"]
t1 : [["a", "b", "c"], ["a", "c", "b"], ["b", "a", "c"], ["b", "c", "a"], ["c", "a", "b"], ["c", "b", "a"]]
t2 : [["a", "b"], ["a", "c"], ["b", "a"], ["b", "c"], ["c", "a"], ["c", "b"]]

When permutation method are not provide parameter value then this method are work on default size which is based on size of given array. In second case when provide parameter values its work is work on given parameter value.

In this example Enumerator is converting into array and print its elements. We can easily iterate Enumerator using each statement. See this example.

# Our array
record  = ["a","b","c"]

# Return Enumerator
e = record.permutation(2)

# Display result
["a", "b"]
["a", "c"]
["b", "a"]
["b", "c"]
["c", "a"]
["c", "b"]

This method returns the self array when providing blocks..

# Our array
record  = [1,4,5,6]

# Return Enumerator
r = record.permutation(2){
  # Check if data include 1 
print("\n return r : ",r);
Ruby permutation method example 2
[1, 4][1, 5][1, 6][4, 1][5, 1][6, 1]
 return r : [1, 4, 5, 6]

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment

© 2021,, All rights reserved