Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Kernel#then

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"

Good usage for 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 block, the method returns 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.4 · 3.3 · 3.1 · 3.0