instance method
Kernel#then
() -> ::Enumerator[self, untyped]
[T] () { (self) -> T } -> T
obj.then {|x| block } → an_object
kernel.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/kernel.rb, line 121
def then
Primitive.attr! :inline_block
unless defined?(yield)
return Primitive.cexpr! 'SIZED_ENUMERATOR(self, 0, 0, rb_obj_size)'
end
yield(self)
end
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