Commit 211710d7 authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #1964 from ksss/object-tap

Implement Object#tap
parents 458c18cd d3ea800c
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 ...@@ -7,3 +7,19 @@ assert('Object#instance_exec') do
k = KlassWithSecret.new k = KlassWithSecret.new
assert_equal 104, k.instance_exec(5) {|x| @secret+x } assert_equal 104, k.instance_exec(5) {|x| @secret+x }
end 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
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment