【问题标题】:ruby send method passing multiple parametersruby send 方法传递多个参数
【发布时间】:2012-11-27 13:15:06
【问题描述】:

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

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

什么时候可以正常工作

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

但抛出错误数量的参数 1 for 2 for

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​​ 方法发送多个参数

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您可以交替调用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__。按照惯例,从来没有人用那个名字写过方法,所以内置的 Ruby 版本总是可用的,并且永远不会与新编写的方法发生冲突。它看起来很奇怪,但从方法名称冲突的角度来看,它比普通发送版本更安全”

    Black 还建议将对 __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。曼宁,2009 年。第 171 页。

    *我来这里是为了寻找__send__ 的哈希语法,所以可能对其他谷歌用户有用。 ;)

    【讨论】:

      【解决方案2】:
      send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator
      

      send(:i_take_multiple_arguments, 25.0, 26.0)
      

      【讨论】:

      • 可能值得注意的是,* 在此上下文中是“splat”运算符。
      猜你喜欢
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2015-12-21
      相关资源
      最近更新 更多