Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
Ruby: agregar un temporizador a una aplicación de prueba de consola simple

Estoy aprendiendo Ruby y, como parte de la práctica, implementé una aplicación de prueba simple. Su pseudocódigo es así

 for i in 0..questions.length - 1 do puts questions[i] $answer = gets.chomp if $answer == answers[i] correct += 1 end end timer_thread = Thread.new do while $answer == nil (1..5).each do |number| sleep(1) number if number == 5 puts "Timer out" end break if ($answer != nil) end end end

Lo que quiero es agregar un temporizador de, digamos, 30 segundos, debería pasar a la siguiente pregunta y esa pregunta debería considerarse incorrecta. Conocí Time.now pero no estoy seguro de cómo puedo agregarlo a mi programa.

¿Algún consejo, por favor?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Creo que usar hilos es una sobrecarga aquí

Puedes usar Timeout

Como veo que usa dos matrices para preguntas y respuestas, puede comprimirlo con Array#zip

En Ruby no nos gusta el bucle for . Usamos Array#each . Por cierto for usos each debajo del capó

El uso de variables globales en el código puede dar lugar a un tiro en el pie. Úselos solo cuando esté absolutamente seguro de que son necesarios

Así que sugeriría refactorizar el código de esta manera:

 require "timeout" correct_answers_count = 0 TIMEOUT = 30 questions.zip(answers).each do |question, right_answer| puts question user_answer = nil Timeout::timeout(TIMEOUT) { user_answer = gets.strip } if user_answer&.downcase == right_answer&.downcase correct_answers_count += 1 puts "Right!" else puts "Wrong!" end rescue Timeout::Error puts "Time is out" end puts "Right answers: #{correct_answers_count}"
over 4 years ago · Santiago Trujillo Report

0

Puedes usar timeout . Establezca el tiempo de espera deseado en segundos cambiando time_to_answer , en este ejemplo se establece en 5.

 require 'timeout' questions = [ "2 + 2 = ?", "Who is Amazons CEO?", ] answers = [ "4", "Jeff Bezos", ] def ask_question(question, answer, time_to_answer) puts "\n=== NEW QUESTION ===" puts question Timeout::timeout(time_to_answer) do user_action = gets.chomp return user_action === answer end rescue Timeout::Error puts "🚧 time is up! solution: #{answer}" return false end time_to_answer = 5 # in seconds score = 0 # initialize score questions.each_with_index do |question, indx| correct = ask_question(question, answers[indx], time_to_answer) score += 1 if correct puts correct ? "✅ correct" : "❌ wrong! correct solution: #{answers[indx]}" end puts "\n🎉 Your score is #{score} out of #{questions.size}"
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!