Implement Object#tap

This commit is contained in:
ksss
2014-03-27 19:35:15 +09:00
parent 458c18cd4e
commit d3ea800cba
2 changed files with 35 additions and 0 deletions
+19
View File
@@ -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
+16
View File
@@ -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