rvdp
rvdp

Reputation: 521

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. Is there any way to call this method with those parameters?

Upvotes: 1

Views: 1540

Answers (1)

sawa
sawa

Reputation: 168269

The method you are looking for is 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.
  • Your regex looks complicated. I made it look simple.
  • Don't forget to use the splat operator *, which decomposes an array.

Upvotes: 1

Related Questions