【发布时间】:2010-12-02 23:39:49
【问题描述】:
我知道Object#tap,它接受一个值并返回该值。但是有没有一种方法可以接受一个块并返回该块评估的值?
为了改进我在this answer 中的代码(比下面的sn-p 更复杂),我想更改
deck.index("A").tap {|index|
STDERR.puts "Result of indexing for #{"A".inspect} is #{index.inspect}"
}
,其中有 "A" 重复,进入
def my_method(*args)
yield *args
end
deck = ['A', 'B', 'C']
my_method("A") {|value| deck.index(value).tap {|index|
STDERR.puts "Result of indexing for #{value.inspect} is #{index.inspect}"
} }
# Result of indexing for "A" is 0
# => 0
【问题讨论】: