Code & Clay – Notes to self. Mainly Ruby/Rails.

What does the then method do in Ruby?

Object#then yields the value of the object to a block and returns the resulting value of the block.

As with #tap, #then helps us negate the need for temporary variables:

> sum = [1,2,3].sum
=> 6

> square = sum ** 2
=> 36

> "The result is #{square}!"
=> "The result is 36!"

The above example becomes:

[1,2,3].sum.then { |obj| obj ** 2 }
           .then { |obj| "The result is #{obj}!" }

Continuing the #tap example, perhaps we want to give a new user a random name:

class Name
  def self.random
    %w{ Lavender Sage Thyme }.sample
  end
end

It’s a little convoluted perhaps, but we can create a new randomly named user in a single line.

Name.random.then { |random_name| User.new.tap { |user| user.name = random_name } }

Name.random.then yields the random name to a block wherein we create a new user. Following the example from the previous post, we then assign the newly instantiated name inside the #tap block.

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6