ruby send方法传递多个参数

rai*_*eep 120 ruby

尝试动态创建对象和调用方法

Object.const_get(class_name).new.send(method_name,parameters_array)
Run Code Online (Sandbox Code Playgroud)

这工作正常

Object.const_get(RandomClass).new.send(i_take_arguments,[10.0])
Run Code Online (Sandbox Code Playgroud)

但为2输入错误数量的参数1

Object.const_get(RandomClass).new.send(i_take_multiple_arguments,[25.0,26.0])
Run Code Online (Sandbox Code Playgroud)

定义的随机类是

class RandomClass
def i_am_method_one
    puts "I am method 1"
end
def i_take_arguments(a)
    puts "the argument passed is #{a}"
end
def i_take_multiple_arguments(b,c)
    puts "the arguments passed are #{b} and #{c}"
end
    end
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我如何动态地发送多个参数到ruby方法

小智 219

send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator
Run Code Online (Sandbox Code Playgroud)

要么

send(:i_take_multiple_arguments, 25.0, 26.0)
Run Code Online (Sandbox Code Playgroud)

  • 可能值得注意的是,在这种情况下,`*`是"splat"运算符. (21认同)

Ton*_*nin 6

你也可以send用它的同义词来调用它__send__:

r = RandomClass.new
r.__send__(:i_take_multiple_arguments, 'a_param', 'b_param')
Run Code Online (Sandbox Code Playgroud)

顺便说一句*你可以像下面这样用逗号分隔哈希:

imaginary_object.__send__(:find, :city => "city100")
Run Code Online (Sandbox Code Playgroud)

或新的哈希语法:

imaginary_object.__send__(:find, city: "city100", loc: [-76, 39])
Run Code Online (Sandbox Code Playgroud)

根据Black的说法,__send__命名空间更安全.

"发送是一个广泛的概念:发送电子邮件,将数据发送到I/O套接字,等等.程序定义一个名为send的方法与Ruby的内置send方法冲突的情况并不少见.因此,Ruby为您提供了另一种调用send的方法:__send__.按照惯例,没有人用该名称编写方法,因此内置的Ruby版本始终可用,并且永远不会与新编写的方法发生冲突.它看起来很奇怪,但从方法名称冲突的角度看它比普通发送版本更安全"

布莱克还建议包装调用__send__if respond_to?(method_name).

if r.respond_to?(method_name)
    puts r.__send__(method_name)
else
    puts "#{r.to_s} doesn't respond to #{method_name}"
end
Run Code Online (Sandbox Code Playgroud)

Ref:Black,David A.有条不紊的Rubyist.Manning,2009.P.171.

*我来这里寻找哈希语法__send__,因此可能对其他googlers有用.;)