如何为类的每个实例打印实例变量的值?

时间:2014-12-17 13:59:23

标签: ruby arrays

我希望打印出FamilyMember类的每个实例的名称和状态变量。我创建了实例并将它们添加到数组中。当我尝试使用.each方法遍历数组时,名称和状态变量不会重新标记。任何帮助将不胜感激。

class FamilyMember
  attr_reader :name, :age, :sex, :status, :country



  def initialize (name, age, sex, status, country)
    @name = name
    @age = age
    @sex = sex
    @status = status
    @country = country

  end

  def parent?

  end

  def child?

  end
end

班级实例

fm1 = FamilyMember.new('Scott', 18 , 'Male', 'Employed', 'America'),
fm2 = FamilyMember.new('Stephen', 30, 'Male', 'Employed', 'Ireland'),
fm3 = FamilyMember.new('Gillian', 50, 'Female', 'Employed', 'Ireland'),
fm4 = FamilyMember.new('Rolf', 56, 'Male', 'Employed', 'Ireland'),
fm5 = FamilyMember.new('Shane', 14, 'Male', 'Unemployed', 'Ireland')

创建数组

array_1 = Array.new

向数组中添加元素

array_1 << fm1
array_1 << fm2
array_1 << fm3
array_1 << fm4
array_1 << fm5


array_1.each do |p| #Trying to print out the name and status values for each instance.
  puts "#{p.name} is #{p.status}"
end

1 个答案:

答案 0 :(得分:3)

您的问题是您使用,结束了代码中的每个实例创建行。这就是为什么fm1实际上是作为数组而不是FamilyMember

创建的原因
fm1.class
# => Array

只需删除行尾的,

fm1 = FamilyMember.new('Scott', 18 , 'Male', 'Employed', 'America')
fm2 = FamilyMember.new('Stephen', 30, 'Male', 'Employed', 'Ireland')
fm3 = FamilyMember.new('Gillian', 50, 'Female', 'Employed', 'Ireland')
fm4 = FamilyMember.new('Rolf', 56, 'Male', 'Employed', 'Ireland')
fm5 = FamilyMember.new('Shane', 14, 'Male', 'Unemployed', 'Ireland')

再试一次:

array_1 = Array.new
array_1 << fm1
array_1 << fm2
array_1 << fm3
array_1 << fm4
array_1 << fm5


array_1.each do |p|
  puts "#{p.name} is #{p.status}"
end

输出:

Scott is Employed
Stephen is Employed
Gillian is Employed
Rolf is Employed
Shane is Unemployed