1

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?

2
  • What does your input string look like? I only ask because your regex looks a bit odd. Commented Dec 4, 2011 at 20:02
  • The string looks like method_name paramList where paramList is a variable number of parameters separated by either commas, whitespace or a mix of both. So the regex should decompose this into an array of the form [method_name, param1, param2, ...]. PS: it should actually be %r{[/[[:blank:]]/,]+} I fixed that in the mean time. Commented Dec 5, 2011 at 13:43

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.