Using select, reject, collect, inject and detect.
?
Looping in Ruby seems to be a process of evolution for newcomers to the language. Newcomers will always find their way to the for loop almost immediately and when confronted with iterating an array, the first choice will generally be a for..in:
1234
12312121212121212a = [1,2,3,4]a.detect {|n| n == 3}This returns 3. The value we were looking for. If the value had not been found, then the iterator returns?nil.
So if your head is spinning at this point as to which iterator to use for when, then remember this:
- Use select or reject if you need to select or reject items based on a condition.
- Use collect if you need to build an array of the results from logic in the block.
- Use inject if you need to accumulate, total, or concatenate array values together.
- Use detect if you need to find an item in an array.
By using these iterators you will be one step closer to mastering… Ruby-Fu.
?