简体   繁体   English

带有参数的Ruby instance_exec / instance_eval

[英]Ruby instance_exec / instance_eval with arguments

I'm trying to dynamically call a method given in a string using parameters given in the same string, I'm getting stuck on supplying the parameters though... 我正在尝试使用相同字符串中给定的参数动态调用字符串中给定的方法,但是我一直无法提供参数...

I currently have: 我目前有:

query = Query.new

while true
  input = gets.split(%r{[/[[:blank:]]/,]})
  puts (query.instance_exec(*input.drop(1)) { |x|
    instance_eval input.at(0)
  })
end

So the method name is input(0) and the arguments to this method are in the rest of input. 因此,方法名称为input(0),此方法的参数位于其余输入中。 Is there any way to call this method with those parameters? 有什么方法可以使用这些参数调用此方法?

The method you are looking for is send . 您正在寻找的方法是send Its first argument will be the method, and the rest will be passed to that method. 它的第一个参数是方法,其余参数将传递给该方法。

query = Query.new
puts query.send(*gets.split(/\s+/)) while true
  • You can use while modifier. 您可以使用while修饰符。
  • Your regex looks complicated. 您的正则表达式看起来很复杂。 I made it look simple. 我看起来很简单。
  • Don't forget to use the splat operator * , which decomposes an array. 不要忘记使用splat运算符* ,它分解一个数组。

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

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