Ruby syntax

Asked

Viewed 187 times

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 lines I understand, it will check the size of the vector, and if it is not less than 2 it will create a vector to store the permutations, from there I do not understand

  • I think it’s more logical. << adds an item in an array. The sum of arrays results in a single array, i.e.: [1] + [1] == [1, 1]`.

2 answers

1


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

All that is between keys is a function like any other but with a different syntax because it is an anonymous function. It has no name, only the body, and can be called syntax lambda.

The |e| is the parameter that this function will receive. Whoever calls this function and sends an argument to it is the each() that the language provides is basically the only thing it does, sweeps the entire object 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 execution loop.

He uses the operator << which is the same as saying that a append, that is, it adds items in a vector.

This is called callback.

  • permut(vet - [e]). each{|p| means that it is creating a new array with [and] and subtracting from vet, and then traversing a smaller array, now with p. That’s it?

  • Yeah, that’s right.

  • 1

    @Andersoncarloswoss improved to make it clearer :)

-1

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

"The concept of permutation expresses the idea that distinct objects can be arranged in numerous different orders." (https://en.wikipedia.org/wiki/Permutation)

I think it works as a means of demonstrating/learning what recursion is: "Recursion in programming is well exemplified when a function is defined in terms of itself." (https://pt.wikipedia.org/wiki/Recursivity#Recurs%C3%A3o_em_ci%C3%Aancia_da_computa%C3%A7%C3%A3o)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.