title: How to create a nested loop with Ruby the "Right Way!"?
body: <p>I'm in the process of learning Ruby, taking a Berkeley's MOOC, and, in some of these MOOC's homework we have an exercise that says:</p>
  
  <blockquote>
    <p>Define a method sum_to_n? which takes an array of integers and an
    additional integer, n, as arguments and returns true if any two
    elements in the array of integers sum to n. An empty array should sum
    to zero by definition.</p>
  </blockquote>
  
  <p>I already created two methods that can do the job, but I'm not comfortable with any of them because I think they are not written in the Ruby Way. I hope some of you can help me to learn which would be the right way!</p>
  
  <p>The first method I made uses the <code>each</code> method for both iterations, but what I don't like about this method is that every number is summed with every other number, even with the same number, doing something like this:</p>
  
  <pre><code>arr[1, 2, 3, 4] =&gt; 1+1, 1+2, 1+3, 1+4, 2+1, 2+2, 2+3, 2+4, 3+1, 3+2... 4+3, 4+4
  </code></pre>
  
  <p>As you can see, there's a lot of repeated sums, and I don't want that.</p>
  
  <p>This is the code:</p>
  
  <pre><code>def sum_to_n?(arr, n)
    arr.each {|x| arr.each {|y| return true if x + y == n &amp;&amp; x != y}}
    return true if n == 0 &amp;&amp; arr.length == 0
    return false
  end
  </code></pre>
  
  <p>With the other method I got what I wanted, just a few sums without repeating any of them or even summing the same numbers, but it looks HORRIBLE, and I'm pretty sure someone would love to kill me for doing it this way, but the method does a great job as you can see:</p>
  
  <pre><code>arr[1, 2, 3, 4] =&gt; 1+2, 1+3, 1+4, 2+3, 2+4, 3+4
  </code></pre>
  
  <p>This is the code:</p>
  
  <pre><code>def sum_to_n?(arr, n)
    for i in 0..arr.length - 1
      k = i + 1
      for k in k..arr.length - 1
        sum = arr[i] + arr[k]
        if sum == n
          return true
        end
      end
    end
    return true if n == 0 &amp;&amp; arr.length == 0
    return false
  end
  </code></pre>
  
  <p>Well, I hope you guys have fun doing a better and prettier method as I did trying.</p>
  
  <p>Thank you for your help. </p>