Ruby Hoedown!

Posted by Nathaniel on Mar 27th, 2007

I don’t want to dup the whole post, but in case you don’t follow my personal blog, I just posted over there about the upcoming  Ruby Hoedown 2007. Have a look and make sure to sign up for the announcement list if you’re at all interested in coming. See you in August!

Ruby Tidbit: Enumerable#collect_one

Posted by Nathaniel on Mar 1st, 2007
  module Enumerable
    def collect_one(default=nil)
      inject(default) do |d,e|
        if v = yield(e)
          break v
        else
          d
        end
      end
    end
  end

So this:

  element = %w(a bb ccc).detect{|e| /b/ =~ e}
  size = (element ? element.size : 0)

Becomes this:

  size = %w(a bb ccc).collect_one(0){|e| e.size if /b/ =~ e}

Discussion starter: does the name communicate?

You can still contact Nathaniel at nathaniel@terralien.com