Note: I am a novice at Ruby.
Question: How can i get print3 to print out the array, using an until loop? This may be more simple than I realise, but i've spent a good few hours trying to solve the below. All I can find are 'simple' until loop examples.
I have a method (print3), that I specifically need to use an until-loop on. print3 pulls an array from the input_students method. both methods are below.
I get the following in irb - directory.rb:30:in ``print3``: undefined method
[]for nil:NilClass (NoMethodError).
Line 30 refers to
puts "#{i+1} #{students[i][:name]} (#{students[i][:cohort]}
cohort)"
My code:
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
name = gets.chomp.downcase
while !name.empty? do
students << {name: name, cohort: :november}
puts "Now we have #{students.count} students"
name = gets.chomp.downcase
end
students
end
def print3(students)
i = 0
until i > students.length
puts "#{i+1} #{students[i][:name]} (#{students[i][:cohort]}
cohort)"
i += 1
end
end
Thanks for any help you can provide.
As @Tom Lord mentioned, you want your loop to stop when i == students.length
The first element of the array is index 0, the second is index 1. That means your array is length 2 but there is no element at index 2, since you're incrementing by 1 you want to stop your loop there.