【发布时间】:2021-12-07 18:33:33
【问题描述】:
我最近遇到了这个问题,我很好奇我是否错误地使用了命名参数或者更好地理解它们为什么会这样。
def test_param(b=false)
if b
puts 'param is true'
puts b
puts b.class
else
puts 'param is false'
puts b
puts b.class
end
end
当我在 REPL 中测试这个函数时,我看到了
2.5.3 :213 > test_param(true)
param is true
true
TrueClass
=> nil
2.5.3 :214 > test_param(false)
param is false
false
FalseClass
=> nil
2.5.3 :215 > test_param(b:true)
param is true
{:b=>true}
Hash
=> nil
2.5.3 :216 > test_param(b:false)
param is true
{:b=>false}
Hash
=> nil
2.5.3 :217 >
为什么当我使用命名参数时,变量数据类型被更改为哈希,这似乎错了。
【问题讨论】:
-
当你还没有指定所有参数时,像
any_method(a: 1, b: 2)这样的东西在ruby 2上被解释为any_method({ a: 1, b: 2 }),它只在强制参数之后才算作关键字参数,ruby 3,它计算所有参数后,我知道因为I asked it some months ago,所以在你的情况下,不是“关键字参数转换”,你只是传递一个哈希 -
@saviu-u 那不正确。在 Ruby 3 中,
any_method({ a: 1, b: 2 })将始终被视为位置参数。
标签: ruby