A higher-order function takes another function as an argument or returns a function as its result. In Ruby, blocks and procs provide these function values: methods such as map and inject/reduce accept blocks, while methods can return procs. section 16.3 section 16.3.4
Ruby uses higher-order functions to express several recurring patterns:
- Transform or filter collections by passing a block to methods such as map or select. section 16.3
- Return transformation instructions in a proc, then call that proc after additional information becomes available. section 16.3.4
- Abstract varying arguments with currying, which returns partially applied functions until enough arguments have been supplied. section 16.3.5
- Combine generic functions with lazy enumerators to produce concise computations over potentially unbounded sequences. section 16.4.1
From duplicated methods to a reusable function
Separate methods can find multiples of 3 or 5, but a generic function accepts the divisor and the array: `find_multiples = -> (x, arr) { arr.select { it % x == 0 } }`. Currying specializes the first argument: `find_multiples_of_3 = find_multiples.curry.(3)`. Supplying an array later produces the matching values. section 16.3.5
>> [1,3,5].map { |x| x * 5 }
=> [5, 15, 25]
Run a compact Ruby example showing a block passed to map and the resulting transformed array. section 16.3













