Home>
# Code i am currently writing
animals = ["dog", "cat", "rabbit", "monkey", "elephant", "chameleon"]
for animal in animals do
puts animal
end
answer = animals [1]
5.times do | i |
puts "# {i + 1} th"
if answer == gets.chomp
puts "correct answer"
exit
else
puts "incorrect"
end
end
I am currently making a game to hit animals.
I want to make a different process for the last iteration.
nth time only,
puts "Incorrect! The answer was # {answer}!"
Result: Incorrect! The correct answer was cat!
I want to feel like
-
Answer # 1
-
Answer # 2
each_with_index
I think this should be used.
Related articles
- ruby - rails transaction does not execute the process after rescue
- the output is different between the code using ruby yield and the code that generated the proc object
- ruby - i don't feel that the sql issued by rails has a different format from the sql that i usually write
- ruby - i want to enter the same value for multiple records using securerandom, but different values are entered
- ruby - i want to solve the page transition to a different url ("users/sign_up" → "/users") when a validation
- ruby - why is the display format different between the user model and other models when retrieving the model object in rails con
- ruby - rails tutorial chapter 11 error with different redirect destination and error with flash display
- interactively change the process by keyboard input while executing rails ruby command
- ruby want to save 3 different table data at once
Trends
If limited to this code,
exit
will be used when correct, so after thetimes
loop,puts "Incorrect! The answer was # {answer}!"
I should do it.
Generally, if the number of repetitions is fixed, you can tell how many times the end is, so compare the loop counter with it.
Is this better for the second half? I thought of another way, but I stopped it because it was difficult to understand.