我正在尝试将二维数组输出到控制台;我希望数组中的信息能够很好地格式化,如本问题末尾我想要的输出所示。我的数组创建如下(创建FamilyMember
类的实例):
#family_members.rb
class FamilyMember
attr_accessor :name, :sex, :status, :age
def initialize (name, sex, type, role, age)
@name = name
@sex = sex
@type = type
@role = role
@age = age
end
end
# Below, an array is created called fm; instances of the class are then instantiated within the array elements
fm = {}
fm[1] = FamilyMember.new('Andrew','Male', 'Child', 'Son' , '27' )
fm[2] = FamilyMember.new('Bill','Male', 'Parent', 'Father' , '63' )
fm[3] = FamilyMember.new('Samantha','Female', 'Parent', 'Mother' , '62' )
fm[4] = FamilyMember.new('Thomas','Male', 'Child', 'Dog' , '10' )
fm[5] = FamilyMember.new('Samantha', 'Female', 'Child', 'Dog' , '4' )
我希望能够将数组的内容输出到格式化为字符串的控制台。我需要能够以两种方式做到这一点 - 使用each
和单独使用do
.
我尝试过的(受之前的 SO question 启发):
def eacharray(an_array)
an_array.each do |inner|
puts inner.join(" ")
end
end
eacharray(fm)
但是上面的输出如下:
1 #<FamilyMember:0x000000027e7d48>
2 #<FamilyMember:0x000000027e7c58>
3 #<FamilyMember:0x000000027e7b68>
4 #<FamilyMember:0x000000027e7a78>
5 #<FamilyMember:0x000000027e7988>
如何使用each
和输出格式良好的 2D 数组元素do
?任何帮助表示赞赏。谢谢。
理想情况下,我的输出将是这样的:
Family Member Name Sex Type Role Age
1 Andrew Male Child Son 27
2 Bill Male Parent Father 63
3 Samantha Female Parent Mother 62
4 Thomas Male Child Dog 10
5 Samantha Female Child Dog 4