Chaining Transformations with .then in Ruby

Have you ever found yourself writing a series of operations in Ruby that felt a bit too verbose? The then method, introduced in Ruby 2.6, is a clean and elegant way to chain transformations on a value, avoiding intermediate variables and improving code clarity.

In this post, we’ll understand how then works using a simple and practical example: formatting a blog post title.

Scenario

Imagine you’re working with a blog post title that comes in messy. You want to:

  1. Remove extra whitespace;
  2. Convert everything to lowercase;
  3. Capitalize the first letter of each word.

Traditional code (without .then)

1
2
3
4
5
6
7
title = "   rUBY is     AWESOME   "
trimmed = title.strip
downcased = trimmed.downcase
final_title = downcased.split.map(&:capitalize).join(" ")

puts final_title
# => "Ruby Is Awesome"

This code works perfectly, but we had to create three intermediate variables just to transform a string. What if we could make it cleaner?

Using .then to chain everything

1
2
3
4
5
6
7
8
9
title = "   rUBY is     AWESOME   "

final_title = title
  .strip
  .then { |t| t.downcase }
  .then { |t| t.split.map(&:capitalize).join(" ") }

puts final_title
# => "Ruby Is Awesome"

Notice how using then makes the sequence of operations more fluent and readable. Each transformation step is applied to the result of the previous one, with no need for extra variables.

So what exactly is .then?

The then method acts like a functional pipeline: it takes the previous value and passes it into a block, returning the result of that block.

So this:

1
value.then { |v| do_something_with(v) }

Is equivalent to:

1
2
v = value
do_something_with(v)

But with then, you can keep chaining transformations, making your code more elegant.

Even more compact version

You can also combine then with other direct method calls:

1
2
3
4
5
6
7
final_title = "   rUBY is     AWESOME   "
  .strip
  .downcase
  .then { |t| t.split.map(&:capitalize).join(" ") }

puts final_title
# => "Ruby Is Awesome"

When should you use .then?

Use then when:

When to avoid it?

Avoid then if:

then is a powerful and elegant tool that can make your Ruby code cleaner and more functional. In simple scenarios or data transformation pipelines, it helps chain operations expressively.