0

我想将二维数组的每个元素转换为字符串,each 但我不能使用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):

  • 家庭成员 1 是AndrewMale,一个Child;具体来说,一个 Son年迈的27
  • 家庭成员2是BillMale,一个Parent;具体来说,一个Father年迈的63
  • 家庭成员 3 是SamanthaMale,一个Parent;具体来说,一个Mother年迈的62
  • 家庭成员 4 是ThomasMale,一个Child;具体来说,一个Dog 年迈的10
  • 家庭成员 5 是SamanthaFemale,一个Child;具体来说,一个Dog年迈的4

解决此问题的最佳方法是什么?原谅我缺乏知识,并感谢您的任何帮助 - 不胜感激。

4

3 回答 3

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}"
}
于 2013-09-28T17:32:50.113 回答
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
于 2013-09-28T17:33:38.937 回答
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
于 2013-09-28T17:33:40.387 回答