Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's build this up step-by-step. We will simplify things a bit by taking it out of the class context.</p> <p>For this example it is intuitive to think of an iterator as being a more-powerful replacement for a traditional for-loop. </p> <p>So first here's a for-loop version:</p> <pre><code>seq1 = (0..2) seq2 = (0..2) for x in seq1 for y in seq2 p [x,y] # shorthand for puts [x, y].inspect end end </code></pre> <p>Now let's replace that with more Ruby-idiomatic iterator style, explicitly supplying blocks to be executed (i.e., the <code>do...end</code> blocks):</p> <pre><code>seq1.each do |x| seq2.each do |y| p [x,y] end end </code></pre> <p>So far, so good, you've printed out your cartesian product. Now your assignment asks you to use <code>yield</code> as well. The point of <code>yield</code> is to "yield execution", i.e., pass control to another block of code temporarily (optionally passing one or more arguments).</p> <p>So, although it's not <em>really</em> necessary for this toy example, instead of directly printing the value like above, you can <code>yield</code> the value, and let the caller supply a block that accepts that value and prints it instead.</p> <p>That could look like this:</p> <pre><code> def prod(seq1, seq2) seq1.each do |x| seq2.each do |y| yield [x,y] end end end </code></pre> <p>Callable like this:</p> <pre><code>prod (1..2), (1..2) do |prod| p prod end </code></pre> <p>The <code>yield</code> supplies the product for each run of the inner loop, and the yielded value is printed by the block supplied by the caller.</p>
 

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