我想在each
中将2D数组的每个元素转换为字符串但是我不能使用do
(具体要求 - 这是作业)。该数组名为families
,定义如下:
#family.rb
class FamilyDetails
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 families; instances of the class are then instantiated within the array elements
families = []
families << FamilyDetails.new('Andrew','Male', 'Child', 'Son' , '27' )
families << FamilyDetails.new('Bill','Male', 'Parent', 'Father' , '63' )
families << FamilyDetails.new('Samantha','Female', 'Parent', 'Mother' , '62' )
families << FamilyDetails.new('Thomas','Male', 'Child', 'Dog' , '10' )
families << FamilyDetails.new('Samantha', 'Female', 'Child', 'Dog' , '4' )
我尝试使用join
方法,如下所示:
def arrayeachsearch(an_array)
an_array.each
output = an_array.join(" ")
puts output
end
arrayeachsearch(families)
然而,这导致以下输出:
#<FamilyDetails:0x00000002358110> #<FamilyDetails:0x000000027c7f48> #<FamilyDetails:0x000000027c7e58> #<FamilyDetails:0x000000027c7d68> #<FamilyDetails:0x000000027c7c78>
我希望输出像这样(我已经包围了information from the array like this
):
Andrew
,Male
,Child
;具体来说,a
Son
年龄27
Bill
,Male
,Parent
;
具体而言,Father
年龄为63
Samantha
谁
是Male
,Parent
;具体而言,Mother
年龄为62
Thomas
,Male
,Child
;一个Dog
年龄10
Samantha
,Female
,Child
;
具体而言,Dog
年龄为4
最好的方法是什么?原谅我缺乏知识,感谢任何帮助 - 赞赏。
答案 0 :(得分:2)
如果您将:role
和:type
添加到attr_accessor
,则可以使用:
families.each.with_index(1) { |member, index|
puts "Family member #{index} is #{member.name} who is #{member.sex}, a #{member.type}; specifically, a #{member.role} aged #{member.age}"
}
答案 1 :(得分:1)
class FamilyDetails
attr_accessor :name, :sex, :status, :age
def initialize (i, name, sex, type, role, age)
@i = i
@name = name
@sex = sex
@type = type
@role = role
@age = age
end
def to_s
"Family member #{@i} is #{name} who is #{sex}, a #{type}; specifically, a #{role} aged #{age}"
end
end
然后你可以简单地做
puts families
答案 2 :(得分:1)
在我看来你有一个一维数组,你可能会做类似
的事情counter = 0
for member in families
counter += 1
puts "Family member %i is %s who is %s, a %s, a %s, age %i." %[counter, member.name, member.sex, member.type, member.role, member.age]
end