在ruby中构建函数参数并将它们重用于其他函数

时间:2012-09-27 01:49:48

标签: python ruby

我在Ruby中有几个函数需要使用相同的命名参数参数调用。 离。

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

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

我再次使用**配置,就像在python中的kwargs一样。

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

1 个答案:

答案 0 :(得分:5)

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


Ruby 1.x没有关键字参数的splat运算符(实际上,Ruby 1.x甚至没有具有关键字参数)。相反,你只需要config作为你的最后一个参数,你的函数的用户可以传入一个哈希键,你拉出键:

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

Python 中,您将以这种方式定义foobar

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"})