Ruby には、同じ名前付きパラメーター引数で呼び出す必要がある関数がいくつかあります。元。
config = { 'options' => {'key' => 'val' }, 'stuff' => '123' }
foo(arg1, arg2, **config)
bar(newarg1, newarg2, **config)
繰り返しますが、Python の kwargs のように **config を使用しています。
Rubyで同等のことを行う方法がわかりません。
編集: Ruby 2.0 では splat 演算子とキーワード引数が導入されているため、Ruby >= 2.0 を使用している場合は、foo(arg, keyword: arg_default)
andのみを使用できますfoo(1, **{:keyword => arg})
。Ruby 1.x を使用している場合は、次のことが適用されます。
Ruby 1.x には、キーワード引数用のスプラット演算子がありません (実際、Ruby 1.x にはキーワード引数さえありません)。代わりに、config
最後の引数として単に持つだけで、関数のユーザーは、キーをプルするハッシュを渡すことができます。
foo(arg1, arg2, config)
bar(newarg1, newarg2, config)
Python では、次のように定義foo
します。bar
def foo(arg1, arg2, **config):
# config now contains any keyword arguments passed to foo
そしてそれを呼び出します:
foo(1, 2, some="key", another="value")
# or if you have a hash from elsewhere
foo(1, 2, **{"some": "key", "another": "value"})
Rubyでは、同様の構成が次の方法で実現されます。
def foo(arg1, arg2, config={})
# config is *still* a positional argument even though it has a default value!
# do stuff with your configuration hash
# as if it were a dictionary of keyword args
# for example:
default_config = {:options {:key => 'value'}, :stuff => 123}
config = default_config.merge(config)
end
そして、次のように呼び出されます。
foo(1, 2, :some => 'key', :another => 'value')
# which translates into
foo(1, 2, {:some => 'key', :another => 'value'})
# the {} are optional for the last argument
その Ruby コードを直接Python に変換するとしたら、次のようになります。
def foo(arg1, arg2, config=None):
# This is not *quite* exact because we can still call `foo(1, 2, config={})`
# but I think it is as close as you can get in Python
if config is None:
config = {}
# Now we can do things with the config dictionary.
そして、あなたはそれを呼ぶでしょう:
# Note: no ** (splat) operator in front of our dictionary
foo(1, 2, {"some": "key", "another": "value"})