Techioz Blog

Ruby でメソッドのキーワード パラメータにハッシュとしてアクセスできますか?

概要

同じパラメータで他のメソッドを呼び出すキーワードパラメータを持つメソッドがいくつかあります。現在、各パラメータを手動で渡す必要があります。すべてのキーワードパラメータにハッシュとしてアクセスし、それを直接渡す方法はありますか?

サンプルコード -

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 メソッドのシグネチャを変更することはできません。メソッドが使用されているすべてのコードベースにアクセスできるわけではなく、メソッドのコンシューマを破壊する危険も冒せないからです。私はそれらのロジックと executorX メソッドを完全に制御できます。私の目的は、このコードをリファクタリングして行数を減らし、読みやすさを向上させることです。

ありがとう!

解決策

メソッド呼び出しからネストされたメソッド呼び出しにすべてのキーワード引数を常に渡したい場合は、二重スプラット演算子 (**) を使用するとうまくいきます。

def method1(**)
  # do something specific to method1
  result = executor1(**)
  # do something with result
end