0

Let's say I have an @array = [1 ,2 ,3] I want to create three blocks of each number of the array with the rest like this :

@array.each do |first|
  (@array - [first]).each do |second|
    (@array - [first] - [second]) do |third|
      #do something

So each block iterates through the entire array except the element that's being used by the preceding block. But this is kind of smelly and repetitive, because for each block I need to delete the preceding elements , what is the best way to refactor these blocks?

Thanks

2
  • It is not clear what you want. Give an expected output. Commented Feb 4, 2015 at 22:56
  • Max answered me, looks like it' clear what I am asking to some people. Commented Feb 4, 2015 at 23:03

1 Answer 1

2

The terminology for that is a permutation. Ruby has a built-in method for doing so:

@array.permutation(3) do |first, second, third|
  # do something
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Max, this is what I am looking for. Will accept once I can

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.