Method: Object#then
- Defined in:
- object.c
#then {|x| ... } ⇒ Object #yield_self {|x| ... } ⇒ Object
Yields self to the block and returns the result of the block.
3.next.then {|x| x**x }.to_s #=> "256"
"my string".yield_self {|s| s.upcase } #=> "MY STRING"
Good usage for then is value piping in method chains:
require 'open-uri'
require 'json'
construct_url(arguments).
then {|url| open(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:
# meets condition, no-op
1.then.detect(&:odd?) # => 1
# does not meet condition, drop value
2.then.detect(&:odd?) # => nil
598 599 600 601 602 603 |
# File 'object.c', line 598 static VALUE rb_obj_yield_self(VALUE obj) { RETURN_SIZED_ENUMERATOR(obj, 0, 0, rb_obj_size); return rb_yield_values2(1, &obj); } |