mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Implement Object#tap
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
class Object
|
||||
##
|
||||
# call-seq:
|
||||
# obj.tap{|x|...} -> obj
|
||||
#
|
||||
# Yields <code>x</code> to the block, and then returns <code>x</code>.
|
||||
# The primary purpose of this method is to "tap into" a method chain,
|
||||
# in order to perform operations on intermediate results within the chain.
|
||||
#
|
||||
# (1..10) .tap {|x| puts "original: #{x.inspect}"}
|
||||
# .to_a .tap {|x| puts "array: #{x.inspect}"}
|
||||
# .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
|
||||
# .map { |x| x*x } .tap {|x| puts "squares: #{x.inspect}"}
|
||||
#
|
||||
def tap
|
||||
yield self
|
||||
self
|
||||
end
|
||||
end
|
||||
@@ -7,3 +7,19 @@ assert('Object#instance_exec') do
|
||||
k = KlassWithSecret.new
|
||||
assert_equal 104, k.instance_exec(5) {|x| @secret+x }
|
||||
end
|
||||
|
||||
assert('Object#tap') do
|
||||
ret = []
|
||||
(1..10) .tap {|x| ret << "original: #{x.inspect}"}
|
||||
.to_a .tap {|x| ret << "array: #{x.inspect}"}
|
||||
.select {|x| x%2==0} .tap {|x| ret << "evens: #{x.inspect}"}
|
||||
.map { |x| x*x } .tap {|x| ret << "squares: #{x.inspect}"}
|
||||
|
||||
assert_equal [
|
||||
"original: 1..10",
|
||||
"array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
|
||||
"evens: [2, 4, 6, 8, 10]",
|
||||
"squares: [4, 16, 36, 64, 100]"
|
||||
], ret
|
||||
assert_equal(:tap_ok, Class.new {def m; tap{return :tap_ok}; end}.new.m)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user