lundi 7 novembre 2016

Ruby Calling a method based on an elseif statement

So I'm still chugging along with learning how to code in Ruby and I've come across something new that I'm curious about. My teacher just started teaching us about methods and I was wondering if you could call/create a method based on an if-else statement. Like for example if you had a program that asked the user to type in someone's name could you then use that input to decide which method would be used?

example:

puts "Please enter name(Brian, Andy, Tod)"
string = gets.to_i
if string == "Brian"
   def b(string)
       puts "Hi Brian"
   return b

elsif string == "Andy"
   def a(string)
       puts "Hi Andy"
   return a

elsif string == "Tod"
   def t(string)
       puts "Hi Tod"
   return t
else
   puts "Not a valid entry"
end

I know that code likely does not work, I just created it off the top of my head to clarify what I meant, but is there actually a way to do this?

Aucun commentaire:

Enregistrer un commentaire