Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Ruby Interactive List Creation

Just started Ruby.

Basically I am trying to write a code which will take users input from the terminal and create an array.

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 felix

What I have done so far is below. Not sure if I need a loop? How can I fix the "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}"
end
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In order to enter an arbitrary amount of names, you need some kind of loop. Here's an example without an else-part using loop and 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

But with one puts outside and an additional puts at the loop's end, the code seem a bit out of order.

I'd prefer to keep each round's initial output at the top of the loop, even if the code becomes longer. This can be achieved by using 1.step instead of loop which passes a 1-based counter into the block: (there are many other ways to do this)

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

You also don't need to count the entered names yourself, just ask the array for its element count:


puts "Congratulations! Your Wagon has #{array.count} student(s):"
puts array.join(', ')
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda