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

    If limited to this code,exitwill be used when correct, so after thetimesloop,
    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.

    # Code you are currently writing
    animals = ["dog", "cat", "rabbit", "monkey", "elephant", "chameleon"]
    n = animals.size
    for animal in animals do
      puts animal
    end
    answer = animals [1] # This is a random number
    (n-1) .times do | i |
      puts "# {i + 1} th"
      if answer == gets.chomp
        puts "correct answer"
        break
      else
        if i


    Is this better for the second half? I thought of another way, but I stopped it because it was difficult to understand.

    (1 ... n) .each do | i |
      puts "# {i} th"
      if answer == gets.chomp
        puts "correct answer"
        break
      else
        if (1 ... n-1) === i
            puts "incorrect"
        else
            puts "Incorrect answer! The answer was # {answer}!"
        end
      end
    end

  • Answer # 2

    each_with_index

    I think this should be used.