我有一个名为Family Members
, 的类(在文件中family_members.rb
),其中包含诸如name
, sex
, type
,role
和age
.
我创建了实例,fm1
称为fm2
fm3
fm4
和fm5
。
#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_details
在checkdetails.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>'
有没有办法动态地做到这一点?可能没有全局变量 - 因为这被认为是不好的做法?
谢谢你的帮助。