Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Kernel#then
obj.then {|x| block } → an_object
kernel.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.3.0/kernel.rb, line 129
def then
unless block_given?
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"
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
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) }