从另一个类(或文件)调用类的实例上的方法

时间:2013-09-27 15:57:42

标签: ruby class methods

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

在这个类中,我定义了一个名为age的方法,它检查parent?类的实例是否为Family members type

代码工作正常,但我想知道是否可以在另一个类中定义parent方法(可能是parent?或者只能包含该类),因为这样做使代码更整洁。

有效的代码(但我想改进):

superclass

我尝试在另一个名为#family_members.rb class FamilyMembers attr_accessor :name, :sex, :status, :age def initialize (name, sex, type, role, age) @name = name @sex = sex @type = type @role = role @age = age end # Would Like the ability to put this method in another file or class def parent? parent_or_child = @type role = @role age = @age name = @name if parent_or_child == 'Parent' then puts "Yes, this family member is a parent; more specifically, a #{role} named #{name} who is #{age} years old." else puts "This family member is not a parent, it`s only a child; more specifically, a #{role} named #{name} who is #{age} years old." end end end fm1 = FamilyMembers.new('John','Male', 'Child', "Son" , "27" ) fm2 = FamilyMembers.new("Bill","Male", "Parent", "Father" , "63" ) fm1.parent? 的文件中定义该方法,并使用ParentOrChild.rb将其包含在family_members.rb的顶部。但是当我这样做时,错误消息告诉我它无法加载这样的文件..

require_relative

我还试图在另一个类中定义该方法(在文件#ParentOrChild.rb def parent? parent_or_child = @type role = @role age = @age name = @name if parent_or_child == 'Parent' then puts "Yes, this family member is a parent; more specifically, a #{role} named #{name} who is #{age} years old." else puts "This family member is not a parent, it`s only a child; more specifically, a #{role} named #{name} who is #{age} years old." end end 中:

parent_or_child.rb

但是当我执行上述操作时,错误告诉我存在未定义的方法#parent_or_child.rb class ParentOrChild def parent? parent_or_child = @type role = @role age = @age name = @name if parent_or_child == 'Parent' then puts "Yes, this family member is a parent; more specifically, a #{role} named #{name} who is #{age} years old." else puts "This family member is not a parent, it`s only a child; more specifically, a #{role} named #{name} who is #{age} years old." end end end (指parent?文件。

我使用的是Ruby 2.0,所以我认为使用family_members.rb而不是require_relative是正确的。

关于如何做到这一点的任何建议都会很棒 - 谢谢。

1 个答案:

答案 0 :(得分:1)

这最初是一个评论,但它也是解决方案,所以我将其添加为答案。

听起来你需要研究继承(或子类)。基本上是:

class ParentOrChild < FamilyMembers

这样,子类ParentOrChild将继承父类FamilyMembers

的方法

作为旁注,以问号结尾的方法应该只返回true或false。