ruby - New Item is array keeps replacing the old one -


i trying make list of students gpa using array , hash. uses gets.chomp make array user input teacher can add program. problem having every time add new student replaces old one. doing wrong?

loop   @students = []   puts "what student's name?"       @name = gets.chomp    puts "what students gpa?"   @gpa = gets.chomp.to_f     def add_students      @students << {:name => @name, :gpa => @gpa}         end     add_students   puts @students  end 

you've misdiagnosed problem. it's not each addition replaces last one... reset @students empty array @ top of every iteration of loop.

so, yes, @students have added student, because loop creates empty array, adds student it, prints it, throws away , creates new empty array.

this...

loop @students = [] 

should this...

@students = [] loop 

... @students array created once, outside loop.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -