简体   繁体   English

ruby send方法传递多个参数

[英]ruby send method passing multiple parameters

Trying to create objects and call methods dynamically by 尝试动态创建对象和调用方法

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

which is working fine when 这工作正常

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

but throwing wrong number of arguments 1 for 2 for 但为2输入错误数量的参数1

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

The Random Class defined is 定义的随机类是

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

Can someone help me on how to send mutiple parameters to a ruby method dynamically 有人可以帮助我如何动态地发送多个参数到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)

You can alternately call send with it's synonym __send__ : 你也可以用它的同义词__send__来调用send

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

By the way* you can pass hashes as params comma separated like so: 顺便说一句*你可以像下面这样用逗号分隔哈希:

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

or new hash syntax: 或新的哈希语法:

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

According to Black, __send__ is safer to namespace. 根据Black的说法, __send__对命名空间更安全。

“Sending is a broad concept: email is sent, data gets sent to I/O sockets, and so forth. “发送是一个广泛的概念:发送电子邮件,将数据发送到I / O套接字,等等。 It's not uncommon for programs to define a method called send that conflicts with Ruby's built-in send method. 程序定义一个名为send的方法与Ruby的内置send方法冲突的情况并不少见。 Therefore, Ruby gives you an alternative way to call send: __send__ . 因此,Ruby为您提供了另一种调用send: __send__ By convention, no one ever writes a method with that name, so the built-in Ruby version is always available and never comes into conflict with newly written methods. 按照惯例,没有人用该名称编写方法,因此内置的Ruby版本始终可用,并且永远不会与新编写的方法发生冲突。 It looks strange, but it's safer than the plain send version from the point of view of method-name clashes” 它看起来很奇怪,但从方法名称冲突的角度看它比普通发送版本更安全“

Black also suggests wrapping calls to __send__ in if respond_to?(method_name) . 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. The well-grounded Rubyist. Ref:Black,David A.有条不紊的Rubyist。 Manning, 2009. P.171. Manning,2009。P.171。

*I came here looking for hash syntax for __send__ , so may be useful for other googlers. *我来这里寻找__send__哈希语法,因此可能对其他googlers有用。 ;) ;)

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

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