【发布时间】:2015-10-24 11:23:59
【问题描述】:
我正在开发一个 Ruby 应用程序,我在其中动态调用基于 JSON 数据的方法。松散:
def items
# do something
end
def createItem( name:, data:nil )
# do something that requires a name keyword argument
end
def receive_json(json) # e.g. { "cmd":"createItem", "name":"jim" }
hash = JSON.parse(json)
cmd = hash.delete('cmd')
if respond_to?(cmd)
params = Hash[ hash.map{ |k,v| [k.to_sym, v } ]
method(cmd).arity==0 ? send(cmd) : send(cmd,params)
end
end
如上所示,有些方法不带参数,有些方法带关键字参数。在 Ruby 2.1.0(我正在开发的地方)下,上述两种方法的arity 是0。但是,如果我总是send(cmd,params),我会收到不带参数的方法的错误。
如何在需要时使用send 正确传递关键字参数,但在不需要时忽略它们?
【问题讨论】:
标签: ruby keyword-argument method-dispatch