Higher-order functions are functions that operate on
other functions. Higher-order functions usually either take one or more functions as
an argument or return a function.
Ruby supports functions as mostly first-class objects; they can be created, manipulated,
passed, returned, and called. Anonymous functions are represented as Proc
objects, created with Proc.new or Kernel#lambda:
add = lambda{|a,b| a + b}
add.class # => Proc
add.arity # => 2
# call a Proc with Proc#call
add.call(1,2) # => 3
# alternate syntax
add[1,2] # => 3
Functional Programming | 37
The most common use for blocks in Ruby is in conjunction with iterators. Many programmers
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 a Proc object and passing it to each:
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??™s Enumerable module provides several convenience methods to be mixed in to
classes that are ???enumerable,??? or can be iterated over. These methods rely on an each
instance method, and optionally the <=> (comparison or ???spaceship???) method.
Pages:
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70