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. It is an alias of Object#yield_self.

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.