Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Kernel#then

() -> ::Enumerator[self, untyped]
[T] () { (self) -> T } -> T
obj.then {|x| block } → an_object

Yields self to the block and returns the result of the block.

Example
3.next.then {|x| x**x }.to_s             #=> "256"

A good use of then is value piping in method chains:

Example
require 'open-uri'
require 'json'

construct_url(arguments)
  .then {|url| URI(url).read }
  .then {|response| JSON.parse(response) }

When called without a block, the method returns an Enumerator, which can be used, for example, for conditional circuit-breaking:

Example
# Meets condition, no-op
1.then.detect(&:odd?)            # => 1
# Does not meet condition, drop value
2.then.detect(&:odd?)            # => nil
See also #test #throw #tap #trace_var also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0