Your question is very broad because there are many ways to write it. As a first pass I'd do:
class Intro
CHOICES = {
1 => 'Create a new flash card',
2 => 'View all flash cards',
3 => 'Edit a flashcard',
4 => 'Delete a flashcard',
5 => 'View score and answers',
}
def self.display
loop do
puts "Welcome player! Choose one of the following!"
CHOICES.each do |h|
puts '%d. %s?' % h
end
input = gets.to_i
return input if CHOICES[input]
puts 'Invalid option.'
end
end
def self.select number
puts "#{number} selected!"
end
end
choice = Intro.display
Intro.select(choice)
Your choice of gets.chomp.to_i is better written as gets.to_i.
(1..5).include? input is fine but forces you to edit your code if you add or remove options. Instead, compute the maximum value based on the list of choices, so you only have to add or delete them and everything adjusts.
self.select input probably shouldn't be a separate method. It probably shouldn't be called by display either, but that's mostly a programmer-choice.
Using a class for such a simple piece of code is overkill. It could be simplified to:
CHOICES = {
1 => 'Create a new flash card',
2 => 'View all flash cards',
3 => 'Edit a flashcard',
4 => 'Delete a flashcard',
5 => 'View score and answers',
}
def display
loop do
puts "Welcome player! Choose one of the following!"
CHOICES.each do |h|
puts '%d. %s?' % h
end
input = gets.to_i
return input if CHOICES[input]
puts 'Invalid option.'
end
end
def select number
puts "#{number} selected!"
end
choice = display
select(choice)
Using a class to encapsulate the methods, without using it to have instances of the class gets old very quickly. Ruby allows us to write code using classes, or without. Think of what is concise and simple to understand as you write. Sometimes we start simply and have to back up a little and take another run at it because we decide using classes makes more sense. I usually let the complexity of the program determine that.
Using a series of if/elsif/then statements is sometimes useful. We often can use case/when to clean the code up even more than using if chains:
CHOICES = [
'Create a new flash card',
'View all flash cards',
'Edit a flashcard',
'Delete a flashcard',
'View score and answers',
]
def display
loop do
puts "Welcome player! Choose one of the following!"
CHOICES.each.with_index(1) do |s, i|
puts '%d. %s?' % [i, s]
end
input = gets.to_i
case input
when 1 .. CHOICES.size
return input
else
puts 'Invalid option.'
end
end
end
Replace the previous methods with these and experiment.
...how ('%d. %s?' % [i, s]) [works]
Notice that '%d. %s?' is a String. That'd make % a method of String.
See String#%