Ruby 101 for .NET Developers: Select or Reject? 0

Posted by jeff Friday, March 30, 2007 19:15:00 GMT

How can we be in

If there is no outside

Peter Gabriel, "Not One of Us"

Just a quick post today about a method I don't use every day, but sure comes in handy when I need it: reject.

There are actually a handful of different Ruby classes that provide a reject and/or reject! method, but I only care about Array and Hash, since those are the ones I use most often in Rails coding.

Sometimes you will have a collection of things, and for some reason you want a subset of that collection. A common way is to use the select method, because it takes a block in which you can tell it which things belong in your subset:


    sports = ["Hockey", "Baseball", "Basketball", "Football"]
    popular_usa_sports = sports.select { |sport| sport =~ /^(B|F)/ }

But sometimes it's easier think of your subset by what you don't want instead. For that, use reject instead of select:


    sports = ["Hockey", "Baseball", "Basketball", "Football"]
    popular_usa_sports = sports.reject { |sport| sport == "Hockey" }

Same concept works for hashes as well as arrays. I find that my code can sometimes become more readable this way.

There's also a reject! method which will modify your collection, and the rejected elements are gone forever (hence the exclamation point).

Comment


(won't be published)