我有几个带有关键字参数的方法,它们使用相同的参数调用other methods.目前,我必须手动传递每个参数.有没有一种方法可以将所有关键字参数作为Hash访问并直接传递下go ?
示例代码-
def method1(arg1:, arg2:)
# do something specific to method1
result = executor1(arg1: arg1, arg2: arg2)
# do something with result
end
def method2(arg3:, arg4:, arg5:, arg6:)
# do something specific to method2
result = executor2(arg3: arg3, arg4: arg4, arg5: arg5, arg6: arg6)
# do something with result
end
def method3(arg7:)
# do something specific to method3
result = executor3(arg7: arg7)
# do something with result
end
我能做点什么把代码改成-
def method1(arg1:, arg2:)
# do something specific to method1
args = method1_args_as_a_hash
result = executor1(args)
# do something with result
end
def method2(arg3:, arg4:, arg5:, arg6:)
# do something specific to method2
args = method2_args_as_a_hash
result = executor2(args)
# do something with result
end
def method3(arg7:)
# do something specific to method3
args = method3_args_as_a_hash
result = executor3(args)
# do something with result
end
上下文-在我的代码库中,这些关键字参数的数量已经变得相当多,将它们按原样(或有时稍加修改)传递给executorX
个方法会使代码文件太大,难以阅读.不幸的是,我不能更改methodX
方法的签名,因为我不能访问使用它们的每个代码库,也不能冒险 destruct 它们的任何使用者.我确实完全控制了他们的逻辑和executorX
多种方法.我的目标是重构这段代码,以减少行数并提高可读性.
谢谢!