Acabo de empezar Rubí.
Básicamente, estoy tratando de escribir un código que tomará la entrada de los usuarios desde el terminal y creará una matriz.
Type a student name: felix Type another student name or press enter to finish: Cedric Type another student name or press enter to finish: bob Type another student name or press enter to finish: Congratulations! Your Wagon has 3 students: bob, Cedric and felixLo que he hecho hasta ahora está abajo. ¿No estoy seguro si necesito un bucle? ¿Cómo puedo arreglar el "else"?
new_array = [] count = 0 puts "Type a student name" name = gets.chomp new_array << name count = count + 1 puts "Type another student name or enter to finish" name = gets.chomp if name == "" puts "Congratulations! Your Wagon has #{count} student: #{new_array[0]}" else puts "Type another student name or enter to finish" name = gets.chomp new_array << name count = count + 1 puts "Congratulations! Your Wagon has #{count} student: #{new_array}" endPara ingresar una cantidad arbitraria de nombres, necesita algún tipo de bucle. Aquí hay un ejemplo sin else usando loop y break :
array = [] puts "Type a student name" loop do name = gets.chomp break if name.empty? array << name puts "Type another student name or enter to finish" end Pero con una puts afuera y una puts adicional al final del bucle, el código parece un poco fuera de servicio.
Preferiría mantener la salida inicial de cada ronda en la parte superior del ciclo, incluso si el código se alarga. Esto se puede lograr usando 1.step en lugar de loop que pasa un contador basado en 1 al bloque: (hay muchas otras formas de hacer esto)
1.step do |i| if i == 1 puts "Type a student name" else puts "Type another student name or enter to finish" end name = gets.chomp break if name.empty? array << name end Tampoco necesita contar los nombres ingresados usted mismo, solo pregunte a la matriz por su count de elementos:
puts "Congratulations! Your Wagon has #{array.count} student(s):" puts array.join(', ')