Note that there are some explanatory texts on larger screens.

plurals
  1. POThe most idiomatic way to iterate through a Ruby array, exiting when an arbitrary condition met?
    primarykey
    data
    text
    <p>I want to iterate through an array, each element of which is an array of two integers (e.g. `[3,5]'); for each of these elements, I want to calculate the sum of the two integers, exiting the loop when any of these sums exceeds a certain arbitrary value. The source array is quite large, and I will likely find the desired value near the beginning, so looping through all of the unneeded elements is not a good option.</p> <p>I have written three loops to do this, all of which produce the desired result. My question is: which is more idiomatic Ruby? Or--better yet--is there a better way? I try not to use non-local loop variables in, but <code>break</code> statements look kind of hackish to my (admittedly novice) eye.</p> <pre><code># Loop A pairs.each do |pair| pair_sum = pair.inject(:+) arr1 &lt;&lt; pair_sum break if pair_sum &gt; arr2.max end #Loop B - (just A condensed) pairs.each { |pair| arr1.last &lt;= arr2.max ? arr1 &lt;&lt; pair.inject(:+) : break } #Loop C i = 0 pair_sum = 0 begin pair_sum = pairs[i].inject(:+) arr1 &lt;&lt; pair_sum i += 1 end until pair_sum &gt; arr2.max </code></pre> <p>A similar question was asked at <a href="https://stackoverflow.com/questions/1568288/escaping-the-each-iteration-early-in-ruby/1568445#1568445">escaping the .each { } iteration early in Ruby</a>, but the responses were essentially that, while using <code>.each</code> or <code>.each_with_index</code> and exiting with <code>break</code> when the target index was reached would work, <code>.take(num_elements).each</code> is more idiomatic. In my situation, however, I don't know in advance how many elements I'll have to iterate through, presenting me with what appears to be a boundary case.</p> <p>This is from a project Euler-type problem I've already solved, btw. Just wondering about the community-preferred syntax. Thanks in advance for your valuable time.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload