How to flatten the nested for loops? The problem I am facing is:
I need to interate through a bunch of lists, and there are separated conditions which needs to be satisfied by the list. conditons are not independent.

I care about the situation when all the conditions are matched. 

The solutions I come up is nested interations mixed with conditions on each level, but it is rather ugly and not easy to maintain.

Is there a way for me to improve this code?

[1, 2, 3].each do |n1|
  if n1 == 1
    [1, 2, 3].each do |n2|
      if n2 == 2
        [1, 2, 3].each do |n3|
          if n3 == 3
            [1, 2, 3].each do |n4|
              if n4 == n3 # conditions are dependent
                print n1, n2, n3, n4
              end
            end
          end
        end
      end
    end
  end
end
In your example you iterate over the same collection. In that case I'd write:

[1, 2, 3].repeated_permutation(4).each do |n1, n2, n3, n4|
  if n1 == 1 &amp;&amp; n2 == 2 &amp;&amp; n3 == 3 &amp;&amp; n3 == n4
    p [n1, n2, n3, n4]
  end
end


If instead you need to iterate over different collections, check Enumerable#product. 

Of course, any of these alternatives will perform worse than your original code, since you drop whole groups of permutations when some condition is not satisfied. 

Note that you could create a compact abstraction as efficient as your original code (it would take collections to iterate and conditions -with procs?- over them), but this won't pay off if you are going to use it only once.