问题
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?
回答1:
Yeah, the normal way to do this is to define the methods beforehand then invoke them from the (elsif) conditional:
def b
puts "Hello brian"
end
def a
puts "Hello andy"
end
def t
puts "Hello tod"
end
puts "Please enter name(Brian, Andy, Tod)"
string = gets.chomp
if string == "Brian"
b
elsif string == "Andy"
a
elsif string == "Tod"
t
else
puts "Not a valid entry"
end
when you say a by itself that's the same as saying a() - invoking the method. You could technically define the methods inside the conditional (before invoking them) but this isn't good style and is rarely done.
Some other points -
- these methods don't use the
stringparameter so you can remove it, like I've done gets.to_iis saying "get input and convert it to integer" - not what you want to do here. What you're looking for isgets.chomp, which gets a line of input and removes the\nnewline character from the end (allgetsinput will have a newline character at the end)
Note this conditional chain seems like a good candidate for case, and you can refactor the puts into a single place -
def b
"Hello brian"
end
def a
"Hello andy"
end
def t
"Hello tod"
end
input = gets.chomp
puts case input
when "Brian" then b
when "Andy" then a
when "Tod" then t
else "not a valid entry"
end
or you could use a hash structure instead of methods
puts {
"Brian" => "Hello brian",
"Andy" => "Hello andy",
"Tod" => "Hello tod"
}.fetch(gets.chomp, "Invalid input")
来源:https://stackoverflow.com/questions/40478655/ruby-calling-a-method-based-on-an-elseif-statement