<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: metaprogramming code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Mon, 06 Oct 2008 12:05:24 GMT</pubDate>
    <description>DZone Snippets: metaprogramming code</description>
    <item>
      <title>With object do...</title>
      <link>http://snippets.dzone.com/posts/show/5321</link>
      <description>This code enters the scope of an object, so you can temporarily avoid having to reference it by name.&lt;br /&gt; &lt;br /&gt;Effectively changes the value of 'self' in the block scope. This also enables you to run private methods on the object without using __send__.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def with(object, &amp;block)&lt;br /&gt;    object.instance_eval(&amp;block)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Example of usage:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;numbers = [1, 2, 3]&lt;br /&gt;&lt;br /&gt;with numbers do&lt;br /&gt;	map! { |n| n + 100 }&lt;br /&gt;	reject! { |n| n % 2 == 0}&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;p numbers # =&gt; [101, 103]&lt;br /&gt;&lt;br /&gt;n = 15&lt;br /&gt;n = with n do&lt;br /&gt;    self + 13&lt;br /&gt;end&lt;br /&gt;p n # =&gt; 28&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;This gets much more interesting with complex objects that have lots of attributes and you want strict control over how they're set.</description>
      <pubDate>Thu, 03 Apr 2008 11:03:54 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5321</guid>
      <author>vinterbleg (Simon Ask Ulsnes)</author>
    </item>
  </channel>
</rss>
