Getting to Know the Ruby Core Classes: Enumerable#grep

by Ryan Leavengood

I haven't posted here in a very long time, but I recently got a full-time job using Ruby and Rails (hurray) so Ruby is more on my mind lately. In fact I've gotten a better understanding of what life is like for the average Rails developer by seeing how my co-worker Alex writes his Ruby code. Now Alex is a smart guy, he has been doing web-sites for years, is proficient in ColdFusion, PHP , Flash, HTML and CSS, yet his Ruby code is not always as elegant as he or I would like. Of course I've been using Ruby for almost 6 years so know it quite well (and that is a big reason why I was hired.)

Still even I find the occasional new nugget and figured this blog would be a good forum to expose some of my new insights. This way other Rails developers like Alex who aren't as proficient in Ruby as they would like can benefit from my experience.

Recently I was perusing the documentation for the Enumerable module and took a closer look at the grep method. This method is surprisingly more powerful than it might seem at first glance. To learn more, please continue reading this entry...

8 Comments

Danno
2007-03-26 23:13:47
Not to be a debbie downer, but why not use select for something like this?


animals.select{|a| a.class == "Mammal"}


I dunno, maybe if you could do something useful with it by adding a block?

Ryan Leavengood
2007-03-26 23:20:39
Yeah the only reason to do something like that would be to get the combination of select and map in one operation, though they obviously aren't that hard to chain.


I could probably come up with a better example, but the main point was to show how one could make their own === method.


How about this:
mammal_sounds = animals.grep(Magic.new {|a| a.class == "Mammal"}) {|m| m.sound}


:)

pate
2007-03-27 05:43:00
Nice stuff Ryan. I think this is a great response to the "What do you want to read?" thread from last week. Welcome back to the posting fold. I hope to see more like this soon.
Gregory
2007-03-27 07:45:58
I think this is a great response to the "What do you want to read?" thread from last week


+1. Well, it's at least thing kind of thing I want to read!

Stephen Caudill
2007-03-27 08:33:44
Nice write up Ryan :) This is definitely the kind of content I prefer to see. Little micro slices of usefullness (rather than "this link helped me learn to tie my ruby shoes").


Keep 'em comin'.

Danno
2007-03-27 12:02:12
Oh, in that case, it'd be cool to demonstrate how you can use === with the case statement.
Ryan Leavengood
2007-03-27 12:42:55
Yeah Danno I was thinking of writing another brief article about that actually :)
JEG2
2007-03-29 12:05:33
This blog has missed you very much Ryan. Welcome back and way to make an entrance!