Ruby Syntax

1

What happens in this part here?

def permut(vet)
  return [vet] if vet.size < 2
  perm = []

  vet.each{ |e|
    permut(vet - [e]).each{|p|
      perm << ([e] + p)
    }
  }
  perm
end

The first few lines I understand, it will check the size of the vector, and if it is not smaller than 2 it will create a vector to keep the permutations, from there I do not understand

    
asked by anonymous 17.08.2018 / 23:54

2 answers

1

The object vet can call a method called each , it works very similar to for and could be replaced by it. This syntax refers to the object-oriented paradigm in which the object serves as the basis for executing a custom task. Is there a gain? In my opinion not. There is loss of performance and the syntax becomes weirder, as it is being observed there.

Everything in braces is a function like any other but with a different syntax because it is an anonymous function. It has no name, just the body, and may be called lambda syntax.

The |e| is the parameter that this function will receive. Calling this function and sending an argument to it is each() that the language provides, is basically the only thing it does, it scans the whole object by sending one item at a time to the function you wrote there. The rest is equal to any function. And obviously within the vector there is a permutation (calling the same function recursively ) and the result it makes one more loop

It uses the << operator that is the same as saying that an append , that is, it will add items to a vector.

This is called callback .

    
18.08.2018 / 00:16
-1

In the "def permut (vet)" code declares the "permut" method. Within the same method it calls itself (recursion). It is the permutation implementation:

"The concept of permutation expresses the idea that distinct objects can be arranged in many different orders." ( link )

I think it works as a demonstration / learning medium of what recursion is: "The recursion in programming is well exemplified when a function is defined in terms of itself." ( link )

    
19.08.2018 / 00:51