【问题标题】:Classes in ruby红宝石类
【发布时间】:2012-10-02 20:46:06
【问题描述】:

最近开始学习 ruby​​,我为家庭成员创建了一个包含姓名、年龄、性别、婚姻状况和特征的课程。我正在尝试编写一种方法来确定家庭成员是否为父母以及是否为母亲或父亲。

所以该方法的代码如下:

def is_father?(age, sex)
    if age > 30
      puts "is parent"
          if sex == "Male"
            then puts "is father"
          else puts "not father"
          end
    end
  end

家庭成员可能看起来像这样:

fm1=Family.new("John", "Male", 54, "Married", "Annoying")

这样初始化后:

class Family
  def initialize(name, sex, age, status, trait)
    @fam_name=name
    @fam_sex=sex
    @fam_age=age
    @fam_stat=status
    @fam_trait=trait
  end
end

如果一个人包含前面提到的特征,我如何将年龄+性别传递到这个方法中?提前感谢您的帮助

【问题讨论】:

  • 这里可能需要一些性教育。 :)

标签: ruby class


【解决方案1】:

您必须在初始化期间将数据存储在属性中。稍后您可以在不使用方法参数的情况下使用它们。

例子:

class Family
   def initialize(name, sex, age, status, trait)
    @fam_name=name
    @fam_sex=sex
    @fam_age=age
    @fam_stat=status
    @fam_trait=trait
  end
  def is_parent?; @fam_age > 30;end
  def is_father?
    is_parent? and @fam_sex == "Male"
  end
  def to_s
    result = @fam_name.dup
    if @fam_age > 30
      result <<  " is parent and is "
          if @fam_sex == "Male"
            result << "father"
          else 
            result << "not father"
          end
      end
    result
  end
end

fm1=Family.new("John", "Male", 54, "Married", "Annoying")
puts fm1.ilding is_parent?
puts fm1.is_father?
puts fm1

备注:

  • 我修改了您的is_father? - 以? 结尾的方法通常返回一个布尔值。
  • 我将您的文本构建移至方法to_s。如果您使用puts 打印对象,则会调用to_s
  • 最好避免在方法中使用puts。大多数情况下,最好在调用该方法时返回一个答案字符串并设置puts

也许我误解了你的要求。

如果is_father?不是Family的方法并且你需要访问属性,那么你必须定义一个getter方法:

class Family
  def initialize(name, sex, age, status, trait)
    @fam_name=name
    @fam_sex=sex
    @fam_age=age
    @fam_stat=status
    @fam_trait=trait
  end
  attr_reader :fam_sex
  attr_reader :fam_age
end

fm1=Family.new("John", "Male", 54, "Married", "Annoying")
puts fm1.fam_sex
puts fm1.fam_age


is_father?(fm1.fam_age, fm1.fam_sex)

【讨论】:

  • 非常感谢您的帮助,我会尽快让它工作的!
【解决方案2】:

一旦你初始化了年龄/性别/等,你可以通过@age/@sex/@etc以任何方式使用它们

def is_father?(age = nil, sex = nil)
    if (age || @age) > 30
        puts "is parent"
    end
    if (sex || @sex) == "Male"
        puts "is father"
    else 
        puts "not father"
    end
end

在上面的示例中,如果您将值传递给方法,则将使用它们而不是在初始化时设置的值

【讨论】:

    【解决方案3】:

    使用 Struct 可以节省大量代码

    class Family < Struct.new(:name, :sex, :age, :status, :trait)
      # define methods in usual manner
    end
    
    f = Family.new("John", 'male') #<struct Family name="John", sex="male", age=nil, status=nil, trait=nil>
    

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多