0

我在 Ruby 中有几个函数,我需要使用相同的命名参数参数来调用它们。前任。

config = { 'options' => {'key' => 'val' }, 'stuff' => '123' }

foo(arg1, arg2, **config)
bar(newarg1, newarg2, **config)

我再次使用 **config 在 python 中的 kwargs 中。

我不知道如何在 Ruby 中做同样的事情。

4

1 回答 1

5

编辑: Ruby 2.0 引入了 splat 运算符和关键字参数,所以如果你使用 Ruby >= 2.0,你可以只使用foo(arg, keyword: arg_default)and foo(1, **{:keyword => arg})。如果您使用的是 Ruby 1.x,那么以下内容适用:


Ruby 1.x 没有关键字参数的 splat 运算符(事实上,Ruby 1.x 甚至没有关键字参数)。相反,您只需config将最后一个参数作为最后一个参数,您的函数的用户可以传入一个哈希值,您可以从中提取密钥:

foo(arg1, arg2, config)
bar(newarg1, newarg2, config)

Pythonfoo中,你会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"})
于 2012-09-27T02:50:09.440 回答