Schylar Schylar - 7 months ago 26
Ruby Question

How to call a method using user input

I have 2 methods -- Add and Delete -- I was wanting to call them using user input.

So instead of this long code

def delete; end
def add; end

case gets.chomp
when 'Add'
add
when 'Delete'
delete
end


I'm looking for something along the lines of what the key word
eval
does.

eval gets.chomp


That way if the input is 'add' then it will execute the 'add' method

Any ideas?
Thanks!

Edit---
I'm an idiot. Eval works. It appeared to not be working because I had an error else where. Regardless thanks for the answers!

Answer

Something like this:

def a
    puts "1"
end

def b
    puts "2"
end

while true
    eval(gets.chomp)
end