2

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

在这个类中,我定义了一个名为的方法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.rbusing的顶部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.rbfile.

我使用的是 Ruby 2.0,所以我认为使用require_relative而不是require.

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

4

1 回答 1

1

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

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

class ParentOrChild < FamilyMembers

这样子类 ParentOrChild 将继承父类 FamilyMembers 的方法

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

于 2013-09-27T16:56:08.067 回答