Sponsors


Blog powered by TypePad

« Ruby Refactoring Pattern: "Forward with Default Params" | Main | Resolving Files with TextMate, Subversion, and FileMerge »

December 06, 2006

Ruby Arrays: select(), collect(), and map()

As a former Java developer and new to the concept of blocks, these API options seem perplexing at first.   They're not.  All three take a block.  How they use the block is what distinguishes them.  You should read the RDoc for yourself but, if you want a quick a dirty summary, continue reading this post.

collect {|item|block} and map{|item|block} do the same thing - return an array of things returned by the block.  This is different from returning specific items in the collection being iterated over. 

Which leads me to select

select{|item|block} will return actual collection items being iterated over if, for each item, the block condition evaluates to true. Not the same as returning what the block, itself, may return.  In the case of select, the block would always return an instance of class TrueClass or FalseClass.  Typically, [true, false, ..., true] is not what you're looking for in your resulting array.

Slightly modifying the core RDoc example:

a = ["a", "b", "c", "d"]      #=> ["a", "b", "c", "d"]
a.map {|item|"a" == item}     #=> [true, false, false, false]
a.select {|item|"a" == item}  #=> ["a"]

Happy coding!

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/277049/7058717

Listed below are links to weblogs that reference Ruby Arrays: select(), collect(), and map():

Comments

Thanks for the Array#select example! _m2

Hey Ben,

I searched for "ruby .collect" and your site was the first result, pretty cool :-)

ttyl, Ammar

Ive been to your site like 20 times in the past year or so. Very straightforward simple concise with example. GOOD JOB.

Post a comment

If you have a TypeKey or TypePad account, please Sign In