Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Functional Programming | 37

The most common use for blocks in Ruby is in conjunction with iterators. Many pro-
grammers who come to Ruby from other, more imperative-style languages start out
writing code like this:


collection = (1..10).to_a
for x in collection
puts x
end

The more Ruby-like way to express this is using an iterator,Array#each, and passing
it a block. This is second nature to seasoned Ruby programmers:


collection.each {|x| puts x}

This method is equivalent to creating aProc object and passing it toeach:


print_me = lambda{|x| puts x}
collection.each(&print_me)

All of this is to show that functions are first-class objects and can be treated as any
other object.


Enumerable


Ruby’sEnumerablemodule provides several convenience methods to be mixed in to
classes that are “enumerable,” or can be iterated over. These methods rely on aneach
instance method, and optionally the<=> (comparison or “spaceship”) method.
Enumerable’s methods fall into several categories.


Predicates


These represent properties of a collection that may betrue orfalse.


all?
Returnstrue if the given block evaluates totrue for all items in the collection.


any?
Returnstrue if the given block evaluates totrue for any item in the collection.


include?(x),member?(x)
Returnstrue ifx is a member of the collection.


Filters


These methods return a subset of the items in the collection.


detect,find
Returns the first item in the collection for which the block evaluates totrue,or
nil if no such item was found.


select,find_all
Returns an array of all items in the collection for which the block evaluates to
true.

Free download pdf