Better Ruby Through Functional Programming
by Dean Wampler
Functional Programming (FP) has become interesting lately as the most robust way to write
highly-concurrent applications. However, applying functional ideas can benefit your applications in
other ways, too. This talk will describe the key ideas in functional programming, the
functional-like features that Ruby already supports, and how you can improve your code by leveraging
functional programming ideas.
Ruby supports several functional programming features. You can make variables immutable (value
objects) and you can write functions with no side effects, meaning they don't modify any global or
object state and all the work they do is returned by the functions. These characteristics may sound
restrictive, but they eliminate common bugs, as we will see.
These characteristics also make concurrency easier, as there is no state shared between threads that
requires synchronization! We will examine functional-style concurrency in Ruby, using the Actor
model, for example.
Functions are "first class citizens" in functional programming (as the name might imply), meaning
you can assign them to variables and pass them as arguments to other functions. Of course, Ruby
already supports functions (methods) as first-class citizens and closures are anonymous functions.
Ruby DSL's are naturally declarative in nature, like most functional code. Code simplification is a
major benefit in large, non-trivial applications!
Along the way, we will see a few other useful functional techniques, like ways to avoid using nil
values and better use of arrays, maps, and pattern matching.
When finished, you will have a new appreciation for the benefits that functional programming can
bring to your Ruby projects.
About Dean Wampler
I'm a consultant at Object Mentor, "Uncle Bob's" company. Recently, I've focused on "polyglot and
poly-paradigm programming"; how to combine languages and modularity "paradigms" (OOP, FP,
aspect-oriented programming, etc.) to implement applications in the most effective way. In
particular, I have started using Functional Programming ideas to improve my Ruby code.
My open source projects are Aquarium (aquarium.rubyforge.org), an aspect-oriented toolkit for Ruby,
Contract4J (contract4j.org), a design-by-contract tool for Java, and I've contributed to FitNesse
(fitnesse.org), an acceptance testing tool for many languages.
I blog frequently on the Object Mentor blog, blog.objectmentor.com.