繁体   English   中英

ruby send方法传递多个参数

[英]ruby send method passing multiple parameters

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

Object.const_get(class_name).new.send(method_name,parameters_array)

这工作正常

Object.const_get(RandomClass).new.send(i_take_arguments,[10.0])

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

Object.const_get(RandomClass).new.send(i_take_multiple_arguments,[25.0,26.0])

定义的随机类是

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

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

send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator

要么

send(:i_take_multiple_arguments, 25.0, 26.0)

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

r = RandomClass.new
r.__send__(:i_take_multiple_arguments, 'a_param', 'b_param')

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

imaginary_object.__send__(:find, :city => "city100")

或新的哈希语法:

imaginary_object.__send__(:find, city: "city100", loc: [-76, 39])

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

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

Black还建议在__send__ if respond_to?(method_name)__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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM