Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveSupport: alternative Block execution on empty Enumerable

#1950

i did not find an easy way to specify an alternative action when an iterator had nothing to iterate over.

i am using this for now:

module Enumerable def else(&block)

self.respond_to?('empty?') && self.empty? ? yield : self

end

end

in color :) http://blog.sponagl.de/2009/1/23...

maybe this is usable in general...

Reported by Paul · February 12th, 2009 @ 10:21 AM

State: wontfix
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Pratik
    Pratik
    • State changed from new to wontfix

    This looks interesting. But I'm not sure if this pattern belongs to the core or not. You should probably spark a discussion in the core ML - http://groups.google.com/group/rubyonrails-core

    Thanks.

    August 5th, 2009 @ 02:42 PM

  2. Luca Guidi
  3. Eloy Duran
    Eloy Duran

    @Luca: In the docs you miss the 'do' keyword: “end.else” => “end.else do”. Besides that; verified and I like it! +1

    August 6th, 2009 @ 02:49 PM

  4. Luca Guidi
    Luca Guidi

    Thanks Eloy, I just fixed the rdoc issue and added a couple of test cases.

    August 6th, 2009 @ 03:02 PM

  5. blatyo
    blatyo

    I could definitely see myself using something like this. I would definitely change the name from else though. It's bad practice to use keywords as method names and else provides no context when used by itself. +1 (with some changes)

    August 7th, 2009 @ 02:23 PM

  6. Luca Guidi
    Luca Guidi

    @blatyo which name do you suggest?

    August 7th, 2009 @ 02:43 PM

  7. Paul
    Paul

    i do not think the use of else is bad within this context. it reads nice:

    with.each do this end.else do that end

    using it "standalone" does not make much sense i.m.O.

    elements.else do
    ... end

    an

    if elememts.blank?
    ... end

    is and will be better - regardless of the naming of the method...

    August 7th, 2009 @ 03:24 PM

  8. Evgeniy Dolzhenko
    Evgeniy Dolzhenko

    My take on it is: when_blank

    April 16th, 2010 @ 01:39 PM