[英]How to pass kwargs in ruby function? Based on python example
$ ruby --version
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]
There is example on python: python 上有一个例子:
def any_func(a, b=2, c = 0, d=None):
return c
print(any_func(25, c=30)) # will print 30
How can I do the same on ruby?我怎样才能在 ruby 上做同样的事情?
How "kwargs" is called on ruby?在 ruby 上如何调用“kwargs”? I would like to know it for further searching.
我想知道它以进行进一步搜索。
I tried following code on ruby:我在 ruby 上尝试了以下代码:
#!/usr/bin/env ruby
def any_func(a, b = 2, c = 0, d = nil)
c
end
puts any_func(25, c = 30) # will print 0, 30 is expected
In Ruby you need to use hash-like syntax在 Ruby 中,您需要使用类似哈希的语法
def any_func(a, b: 2, c: 0, d: nil)
c
end
any_func(25, c: 30)
def fun(a=1)
only sets a default value. def fun(a=1)
只设置一个默认值。 And if you have any_func(25, c = 30)
, it means "call any_func
with two arguments, 25 and result of expression c = 30
(that is 30)"如果你有
any_func(25, c = 30)
,这意味着“用两个 arguments, 25 调用any_func
和表达式c = 30
的结果 =3”
Ruby has both positional arguments and keyword arguments. Ruby 具有位置 arguments 和关键字 arguments。 Differing from Python, you can't mix them but have to declare them with their respective syntax and provide them accordingly in method calls.
与 Python 不同,您不能混合使用它们,但必须使用各自的语法声明它们并在方法调用中相应地提供它们。
def any_func(a, b: 2, c: 0, d: nil)
c
end
puts any_func(25, c: 30)
You can refer to the official syntax documentation to learn more about how to declare and call methods with arguments.您可以参考官方语法文档了解更多关于如何使用 arguments 声明和调用方法。
As for your own example of calling your any_func
method with any_func(25, c = 30)
, what happened here is that you have created the local variable c
in the calling context with the value 30
.至于您自己使用
any_func(25, c = 30)
调用您的any_func
方法的示例,这里发生的是您在调用上下文中创建了局部变量c
,其值为30
。 You have also passed this value to the second (optional) argument b
of your method.您还将此值传递给方法的第二个(可选)参数
b
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.