如何将用户获取的数据存储在数组中

时间:2018-09-21 04:17:31

标签: ruby instance-variables

我正在命令行上开发医院管理系统。我想从用户那里获取一个值,将其分配给一个实例变量,然后将其进一步存储在数组中。代码如下:

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

每次输入新值时,它都会覆盖先前的值。

1 个答案:

答案 0 :(得分:1)

无论您写了什么,都会将输入添加到该特定运行的实例变量@doctors上,即该特定@doctor的实例变量。如果您需要将所有医生的详细信息存储在一个实例变量中,请在方法外声明它,然后按如下所示运行它。如果您将医生详细信息存储为像DOCTORS = [[DOCTOR1_DETAILS],[DOCTOR1_DETAILS]]这样的数组,那会更好,您可以通过

@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

或者您可以使用.push方法像这样简单地将整个细节附加到数组中

@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