将2D数组转换为字符串

时间:2013-09-28 17:10:41

标签: ruby arrays string

我想在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):

  • 家庭成员1为AndrewMaleChild;具体来说,a Son年龄27
  • 家庭成员2为BillMaleParent; 具体而言,Father年龄为63
  • 家庭成员3是Samantha谁 是MaleParent;具体而言,Mother年龄为62
  • 家庭 成员4是ThomasMaleChild;一个Dog 年龄10
  • 家庭成员5为SamanthaFemaleChild; 具体而言,Dog年龄为4

最好的方法是什么?原谅我缺乏知识,感谢任何帮助 - 赞赏。

3 个答案:

答案 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