您可以准备一组函数,然后将两者压缩在一起。像这样的东西:
# stabby lambdas instead of methods. Because methods aren't objects.
func_a = ->(el) { puts "1 for #{el}" }
func_b = ->(el) { puts "2 for #{el}" }
func_c = ->(el) { puts "3 for #{el}" }
arr = ['a', 'b', 'c', 'd']
funcs = [func_a, func_b, func_c, func_a] # reusing func_a
arr.zip(funcs) {|a, f| f.call(a) }
# >> 1 for a
# >> 2 for b
# >> 3 for c
# >> 1 for d
但我的方法是方法,而不是 lambdas ......
这是如何将方法转换为 proc 对象的技巧,以便您可以将它们放入数组中并稍后调用。但是要小心,与常规方法相比,这些调用更昂贵(没关系,除非您已经从 CPU 中挤出周期)
def func_a el; puts "1 for #{el}"; end
def func_b el; puts "2 for #{el}"; end
def func_c el; puts "3 for #{el}"; end
arr = ['a', 'b', 'c', 'd']
funcs = [method(:func_a), method(:func_b), method(:func_c), method(:func_a)] # reusing func_a
arr.zip(funcs) {|a, f| f.call(a) }
# >> 1 for a
# >> 2 for b
# >> 3 for c
# >> 1 for d