gpt4 book ai didi

ruby - **args 作为 Ruby 中的函数参数

转载 作者:行者123 更新时间:2023-12-03 08:28:34 24 4
gpt4 key购买 nike

我知道 **args 被解释为包含传递给函数的所有键值对的哈希,但我不明白为什么它比典型参数更受青睐。例如我有以下两个函数。

def test(some_string, hash)
puts hash
puts hash.class # => Hash
end


def test_two(some_string, **hash)
puts hash
puts hash.class # => Hash
end

调用 test("test string", a: 1, b: 2)test_two("test string", a: 1, b: 2) 会产生完全相同的结果。使用**作为参数值有什么好处?

最佳答案

Ruby 2.7 开始更清晰地区分关键字参数和常规哈希值。 **args 用于关键字参数。一些影响:

def test3(some_string, foo:, **args)
puts args
end

test3('a', foo: 'b', bar: 'c') # => {:bar=>"c"}

但是按预期工作

def test3(some_string, foo:, hash)
puts args
end # => syntax error

def test3(some_string, hash, foo:)
puts args
end # works so far

test3('a', foo: 'b', bar: 'c')
# warning: Passing the keyword argument as the last hash parameter is deprecated
# ArgumentError (missing keyword: :foo)

一旦升级到 ruby​​ 3,警告就会变成错误。

关于ruby - **args 作为 Ruby 中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65852906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com