在ruby中构建函数参数,并将其用于其他函数

2024-10-02 16:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

同样,我在python中的kwargs中使用**config。你知道吗

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


Tags: key函数config参数foobarval命名
1条回答
网友
1楼 · 发布于 2024-10-02 16:33:30

编辑:Ruby2.0引入了splat操作符和关键字参数,因此如果您使用的是Ruby>;=2.0,那么只需使用foo(arg, keyword: arg_default)foo(1, **{:keyword => arg})。如果您使用的是Ruby 1.x,那么以下内容适用:


Ruby1.x没有用于关键字参数的splat操作符(事实上,Ruby1.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"})

相关问题 更多 >