Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's more to yield and blocks than mere looping. </p> <p>The series <a href="http://www.globalnerdy.com/tag/enumerating-enumerable/" rel="noreferrer">Enumerating enumerable</a> has a series of things you can do with enumerations, such as asking if a statement is true for any member of a group, or if it's true for all the members, or searching for any or all members meeting a certain condition.</p> <p>Blocks are also useful for variable scope. Rather than merely being convenient, it can help with good design. For example, the code</p> <pre><code>File.open("filename", "w") do |f| f.puts "text" end </code></pre> <p>ensures that the file stream is closed when you're finished with it, even if an exception occurs, and that the variable is out of scope once you're finished with it.</p> <p>A casual google didn't come up with a good blog post about blocks and yields in ruby. I don't know why.</p> <p><strong>Response to comment</strong>:</p> <p>I suspect it gets closed because of the block ending, not because the variable goes out of scope.</p> <p>My understanding is that nothing special happens when the last variable pointing to an object goes out of scope, apart from that object being eligible for garbage collection. I don't know how to confirm this, though.</p> <p>I can show that the file object gets closed before it gets garbage collected, which usually doesn't happen immediately. In the following example, you can see that a file object is closed in the second <code>puts</code> statement, but it hasn't been garbage collected.</p> <pre><code>g = nil File.open("/dev/null") do |f| puts f.inspect # #&lt;File:/dev/null&gt; puts f.object_id # Some number like 70233884832420 g = f end puts g.inspect # #&lt;File:/dev/null (closed)&gt; puts g.object_id # The exact same number as the one printed out above, # indicating that g points to the exact same object that f pointed to </code></pre>
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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