传递:test导致ArgumentError:参数数量错误(给定0,应为2..3)

时间:2019-07-16 20:54:35

标签: ruby-on-rails ruby ruby-on-rails-5.2

这两项工作

Rails.application.credentials.development
Rails.application.credentials.send(:development)

但是,第一个.test有效,但(:test)无效。

Rails.application.credentials.test
Rails.application.credentials.send(:test)

:test为什么特别?是什么使它不起作用?我得到

[5] pry(#<Cred>)>Rails.application.credentials.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):5:in `test'

1 个答案:

答案 0 :(得分:2)

test是在Kernel模块中定义的私有方法。 Kernel包含在每个红宝石对象中。 当您调用.send(:test)时,此方法将被调用,它需要2或3个参数。

它也可以在其他对象上复制:

[15] pry(main)> :a.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):23:in `test'
[16] pry(main)> 1.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):24:in `test'

编辑

我不确定credentials是什么对象,所以不能肯定地说是这样,但是当您定义method_missing时,它是在直接调用私有方法之前调用的,而不是与{ {1}},请参见下文:

send

EDIT2:

通常比class B def method_missing(*args) puts args end end pry> B.new.send(:test) ArgumentError: wrong number of arguments (given 0, expected 2..3) from (pry):32:in `test' pry> B.new.test test => nil #public_send更安全。它不会让您调用私有方法,而且还会被#send捕获:

#method_missing