Ruby Calling a method based on an elseif statement

雨燕双飞 提交于 2019-12-11 09:13:44

问题


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 -

  1. these methods don't use the string parameter so you can remove it, like I've done
  2. gets.to_i is saying "get input and convert it to integer" - not what you want to do here. What you're looking for is gets.chomp, which gets a line of input and removes the \n newline character from the end (all gets input 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!