Posts Tagged ‘select’
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 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"]