2

我有一个名为Family Members, 的类(在文件中family_members.rb),其中包含诸如name, sex, type,roleage.

我创建了实例,fm1称为fm2 fm3 fm4fm5

#family_members.rb

require_relative 'family'
require_relative 'checkdetails'

class FamilyMembers < Family

  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

fm1 = FamilyMembers.new('Andrew','Male', 'Child', "Son" , "27" )
fm2 = FamilyMembers.new("Bill","Male", "Parent", "Father" , "63" )
fm3 = FamilyMembers.new("Samantha","Female", "Parent", "Mother" , "62" )
fm4 = FamilyMembers.new("Thomas","Male", "Child", "Dog" , "10" )
fm5 = FamilyMembers.new("Samantha", 'Female', "Child", "Dog" , "4" )

我有一个名为Parent?检查类的实例是 aParent还是 a 的方法Child,它的调用如下所示:

#check_details   //would like to use this method

fm4.parent?

用户是否可以动态选择要检查的类的哪个实例?

我创建了一个方法,check_detailscheckdetails.rb文件中调用:

#checkdetails.rb

def check_details
  puts "What family to you want to check? choose 1 to 5"
  $family = 'fm' + gets.chomp
end

但是,如果我尝试parent像这样调用该方法:

check_details

$family.parent?

它给了我以下错误:

`<top (required)>': undefined method `parent?' for "fm1":String (NoMethodError)
    from -e:1:in `load'
    from -e:1:in `<main>'

有没有办法动态地做到这一点?可能没有全局变量 - 因为这被认为是不好的做法?

谢谢你的帮助。

4

1 回答 1

0

将您的 FamilyMembers 存储在数组或哈希中,然后通过键查找它们。

fm = {}
fm[1] FamilyMembers.new('Andrew','Male', 'Child', "Son" , "27" )
fm[2] = FamilyMembers.new("Bill","Male", "Parent", "Father" , "63" )
fm[3] = FamilyMembers.new("Samantha","Female", "Parent", "Mother" , "62" )
fm[4] = FamilyMembers.new("Thomas","Male", "Child", "Dog" , "10" )
fm[5] = FamilyMembers.new("Samantha", 'Female', "Child", "Dog" , "4" )

answer = "3" # get this from the user.
num = answer.to_i

if fm.key?(num)
  fm[num].parent?
else 
  raise 'Invalid answer'
end

PS Ruby 指南建议“FamilyMembers”类应称为“FamilyMember”。

于 2013-09-27T18:02:21.467 回答