我知道这是一篇旧帖子,但我在尝试解决类似问题时发现了它。
这是一个非常优雅的解决方案,最重要的是,它可以在有或没有回调的情况下工作。
假设我们有一个 Arithmetic 类,它实现了对它们的基本操作 - addition 和 subtraction。
class Arithmetic
def addition(a, b)
a + b
end
def subtraction(a, b)
a - b
end
end
我们想为每个操作添加一个回调,它会对输入数据和结果做一些事情。
在下面的示例中,我们将实现 after_operation 方法,该方法接受将在操作后执行的 Ruby 块。
class Arithmetic
def after_operation(&block)
@after_operation_callback = block
end
def addition(a, b)
do_operation('+', a, b)
end
def subtraction(a, b)
do_operation('-', a, b)
end
private
def do_operation(sign, a, b)
result =
case sign
when '+'
a + b
when '-'
a - b
end
if callback = @after_operation_callback
callback.call(sign, a, b, result)
end
result
end
end
与回调一起使用:
callback = -> (sign, a, b, result) do
puts "#{a} #{sign} #{b} = #{result}"
end
arithmetic = Arithmetic.new
arithmetic.after_operation(&callback)
puts arithmetic.addition(1, 2)
puts arithmetic.subtraction(3, 1)
输出:
1 + 2 = 3
3
3 - 1 = 2
2