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!
Thanks for the Array#select example! _m2
Posted by: m2 | March 10, 2007 at 03:49 PM
Hey Ben,
I searched for "ruby .collect" and your site was the first result, pretty cool :-)
ttyl, Ammar
Posted by: Ammar Yousuf | December 05, 2007 at 10:43 PM
Ive been to your site like 20 times in the past year or so. Very straightforward simple concise with example. GOOD JOB.
Posted by: PICO | May 14, 2008 at 12:27 PM