Functional programming emphasizes computation through functions while minimizing mutable state and side effects. Ruby supports this style without guaranteeing immutability or referential transparency, so functional and object-oriented approaches can coexist. section 16.0
A functional approach favors:
- Pure functions that return the same result for the same arguments without side effects. section 16.1
- New values instead of changing existing state where practical. section 16.1
- Attention to side effects beyond mutation: an unhandled exception can also interrupt a program unexpectedly. section 16.1.3
- Reusable functions and lazy evaluation to work with large or infinite sequences. section 16.4.1
Make a new value instead of reassigning
Rather than incrementing num with `num = num + 1`, keep the original and assign the result to `new_num = num + 1`. Both are valid Ruby, but the latter avoids changing the existing variable's value. section 16.1
Table 16.1 Properties of functional and object-oriented programming styles
| Property |
Object-oriented |
Functional |
|---|---|---|
| Promotes code reuse |
√ |
√ |
| Models behavior with objects |
√ |
|
| Separates data and behavior |
√ |
|
| Promotes encapsulation |
√ |
√ |
| Terse code |
√ |
|
| Generic routines |
√ |
|
| Modularity |
√ |
|
| Flexibility with polymorphism |
√ |
Compare functional and object-oriented styles across reuse, encapsulation, modularity, and other properties. section 16.0
Functional techniques do not eliminate every side effect: useful programs may need to persist data, print output, or update a view. Choose between styles—or combine them—according to the trade-offs. section 16.1.3 section 16.0


















