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

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
    return nil

and then of course, I tested it:

require "test_helper"

require "enumerable_extensions"

class EnumerableTest  2 }

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

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

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

3 responses to “Another useful collection method? Enumerable#select_first”

  1. grrrisu Avatar

    There’s detect in Enumerable. May you where looking for that:

  2. Rymaï Avatar

    Also known as #find!


    1. J. Pablo Fernández Avatar

      find doesn’t take a block to use as the predicate for which item should be returned

Leave a Reply

You may also like:

If you want to work with me or hire me? Contact me

You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 5,043 other subscribers

I wrote a book:

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Kubuntu Lisp management Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek technology Ubuntu web Windows WordPress

I've been writing for a while:


%d bloggers like this: