Home > Net >  Ruby Interactive List Creation
Ruby Interactive List Creation

Time:10-09

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

CodePudding user response:

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(', ')
  • Related