Another useful collection method? Enumerable#select_first

For a personal project I’m working on, I need to find out the smallest time period with more than 5 records. I essentially wrote this code:

period = [1.week, 1.month, 1.year].select_first do |period|
  Record.where("published_at >= ?", period.ago).count >= 5
end

only to find out that the select_first method doesn’t exist. So I wrote it:

module Enumerable
  def select_first(&predicate)
    self.each do |item|
      if yield(item)
        return item
      end
    end
    return nil
  end
end

and then of course, I tested it:

require "test_helper"

require "enumerable_extensions"

class EnumerableTest  2 }
  end

  should "select_first the first one" do
    assert_equal 1, [1, 2, 3, 4].select_first { |i| i >= 1 }
  end

  should "select_first the last one" do
    assert_equal 4, [1, 2, 3, 4].select_first { |i| i >= 4 }
  end

  should "select_first none" do
    assert_equal nil, [1, 2, 3, 4].select_first { |i| i >= 100 }
  end
end
Advertisements

3 thoughts on “Another useful collection method? Enumerable#select_first

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s