动态调用类的实例上的方法(User动态指定实例名称)

时间:2013-09-27 17:51:17

标签: ruby class dynamic methods user-input

我有一个名为Family Members的类(在文件family_members.rb中),其中包含namesextype,{{等属性1}}和role

我创建了名为agefm1 fm2 fm3fm4的实例。

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?还是Parent,并且调用如下所示:

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?

有没有办法动态地执行此操作?可能没有全局变量 - 因为这被认为是不好的做法?

感谢您的帮助。

1 个答案:

答案 0 :(得分: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

P.S。 Ruby指南建议将“FamilyMembers”类称为“FamilyMember”。