我有一个名为Family Members
, 的类(在文件中family_members.rb
),其中包含诸如name
, sex
, type
,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
using的顶部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?
(指的是family_members.rb
file.
我使用的是 Ruby 2.0,所以我认为使用require_relative
而不是require
.
关于如何做到这一点的任何建议都会很棒 - 谢谢。