0

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!

4 Answers 4

1

Something like this:

def a
    puts "1"
end

def b
    puts "2"
end

while true
    eval(gets.chomp)
end
Sign up to request clarification or add additional context in comments.

Comments

1

You can invoke methods by symbol using send:

send gets.chomp

Comments

0

your code should work if tweeked like this:

def delete; end
def add; end

puts "please chose a method add or delete"
ans = gets.chomp.downcase

case ans
    when 'add'
      add
    when 'delete'
      delete
    else 
puts "nothing selected"
end

1 Comment

I specifically said I didn't want a case statement like code
0

You can use "send" method, first put your methods in a class then Try this:

    class Methods
       def show
         print "show"
       end
     end
    print "Enter your method name: "
    methodName = gets.chomp
    methodName.to_sym
    myMethods = Methods.new
    meMethods.send(methodName)

Try it! You can use this way to make new programming languages or HUGE programs.

1 Comment

I ment at the last line myMethods not meMethods

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.