【问题标题】:Array of objects as a field in a class. How to access parameters of single object?对象数组作为类中的字段。如何访问单个对象的参数?
【发布时间】:2018-04-21 10:49:05
【问题描述】:

我昨天开始使用 Ruby,但遇到了问题。 我有两个类:Patient 和 Patient_history。 患者可能有多种病史(来自不同的约会)。

这是我现在拥有的:

class Patient
    attr_accessor :name,
                  :surname,
                  :histories

def initialize(*)
  @histories = []
end

def create_patient
  @name = create_name_or_surname( "name")
  @surname = create_name_or_surname("surname")
end

def create_name_or_surname( name_or_surname)
  #not relevant in this case
end

def add_history(history)
  @histories.push(history)
end

def print_patient
  puts "name: #{@name}"
  puts "surname : #{@surname}"

  ## I wish to do sth like:
  ## puts "history date: #{@histories[1].date}"
  ## to print content of Patient_history

end
end

还有

class Patient_history
   attr_accessor :date,
                 :description

  def create_history
    @date = create_date_or_desc("What is the date today?")
    @description = create_date_or_desc("Write about an illness:")
  end
end

用一行: 病人 在设置历史和患者值后,我得到:

What is your name?
john
What is your surname?
smith
What is the date today?
12/12/2016
Write about an illness:
sick
#<Patient:0x007ffcb50ab518 @histories=[#
<Patient_history:0x007ffcb50aad98 @date="12/12/2016", 
@description="sick">], @name="john", @surname="smith">

你能告诉我该怎么做吗?

【问题讨论】:

  • 注意:应该是initialize 而不是initialize(*)
  • 所以您的p patient 看起来不错...我可以看到患者记录,并且它包含一系列历史记录。你现在想让它做什么?
  • 做什么做什么?
  • 我希望从 Patient 获取那个 patient_history 对象,这样我就可以从方法 def print_patient 中打印出 Patient 和历史记录。我用那种方法评论了我的意图:)

标签: arrays ruby object


【解决方案1】:

问题有点模糊,您要打印出病史列表吗?您可以使用#each 遍历每个历史记录。

def print_patient
  puts "name: #{@name}"
  puts "surname : #{@surname}"

  histories.each do |history|
    puts "History Date: #{history.date}"
    puts history.description
  end
end

【讨论】:

  • 是的!谢谢!
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2018-04-16
相关资源
最近更新 更多