<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>something learned comments on A little (more) syntactic sugar in Rails</title>
    <link>http://somethinglearned.com/</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>something learned comments</description>
    <item>
      <title>"A little (more) syntactic sugar in Rails" by trevor</title>
      <description>&lt;p&gt;This little extension to Ruby&amp;#8217;s Array class is making the rounds:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
class Array
  def sum
    inject(0) { |m, v| m + v }
  end
end

# Use it thusly:
[1,2,3,4,5].sum # =&amp;gt; 15
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Nice.  But what if we want to sum a &lt;em&gt;member&lt;/em&gt; of each array element, such as the &amp;#8216;price_cents&amp;#8217; attribute on a bunch of ActiveRecord objects?&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
@order.line_items.collect {|x| x.price_cents}.sum
# or (my preference) using Symbol's to_proc method:
@order.line_items.collect(&amp;#38;:price_cents).sum
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Even with the sugar that Symbol#to_proc adds, it&amp;#8217;s just a bit&amp;#8230; well, &lt;em&gt;blech&lt;/em&gt;.  We can do better:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
class Array
  def sum
    if block_given?
      inject(0) { |m, v| m + yield(v) }
    else
      inject(0) { |m, v| m + v }
    end
  end
end

# Now we can say:
@order.line_items.sum(&amp;#38;:price_cents)
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;That&amp;#8217;s just &lt;em&gt;so&lt;/em&gt; much clearer.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;Update: a recent &lt;a href="http://dev.rubyonrails.org/changeset/4489"&gt;changeset&lt;/a&gt; in the rails trunk adds a &amp;#8216;sum&amp;#8217; method to Enumerable.  It&amp;#8217;s different from what I present above in that it &lt;strong&gt;only&lt;/strong&gt; works with a block &amp;#8211; which is okay for me because that&amp;#8217;s my main usage pattern anyhow.&lt;/em&gt;&lt;/p&gt;

</description>
      <pubDate>Mon, 12 Jun 2006 13:48:56 EDT</pubDate>
      <guid>&lt;a href="/articles/2006/06/12/a-little-more-syntactic-sugar-in-rails"&gt;A little (more) syntactic sugar in Rails&lt;/a&gt;</guid>
      <link>&lt;a href="/articles/2006/06/12/a-little-more-syntactic-sugar-in-rails"&gt;A little (more) syntactic sugar in Rails&lt;/a&gt;</link>
    </item>
  </channel>
</rss>
