-3

I am developing a hospital management system on command line. I want to take a value from a user, assign it to an instance variable, and further store it in an array. The code is as follows:

def doctor_details
  @doctors = Array.new
  puts 'Enter Doctor Name'
  @doc_name = gets
  @doctors << @doc_name 
  puts 'Enter specialization'
  @doc_specialization = gets
  puts 'Availability of doctor'
  @from = Float(gets)
  @to = Float(gets)
end

Every time a new value is entered, it overwrites the previous value.

sawa
  • 165,429
  • 45
  • 277
  • 381
Moriarty
  • 159
  • 2
  • 16
  • The current method posted will take input once, in the next call from irb, the instance value will be reset. keep the array initialization outside of method or replace \@doctors = Array.new with @doctors ||= Array.new. I would also suggest use hash to keep the details of doctor with their specific specialization and availability. – Bijendra Sep 21 '18 at 04:53
  • you're pushing only doctor's name to array. How it will overwrites the previous value? – uday Sep 21 '18 at 07:38

1 Answers1

1

Whatever you have written it will append the input to the instance variable @doctors for that particular run i.e for that particular @doctor. If you need want to store the details of all the doctors in one instance variable then declare it outsite of the method and then run it like below. It will be better if you store the doctor details as array of arrays like DOCTORS = [[DOCTOR1_DETAILS],[DOCTOR1_DETAILS]] you can do this by

@DOCTORS = []
def doctor_details
  @doctor =[]
  puts 'Enter Doctor Name'
  doc_name = gets
  @doctor << doc_name 
  puts 'Enter specialization'
  doc_specialization = gets
  @doctor << doc_specilalization
  puts 'Availability of doctor'
  from = Float(gets)
  to = Float(gets)
  @doctor << from
  @doctor << to
  @doctors << @doctor
end

OR You can simply append the whole details to an array using .push method like this

@doctors = []
def doctor_details
  puts 'Enter Doctor Name'
  doc_name = gets
  puts 'Enter specialization'
  doc_specialization = gets
  puts 'Availability of doctor'
  from = Float(gets)
  to = Float(gets)
  @doctors.push([doc_name,doc_specialization,from,to])
end
Sumanth Madishetty
  • 3,425
  • 2
  • 12
  • 24