如何在Ruby中定义类的特定属性的方法?

时间:2023-01-15 18:47:11

I have some Ruby-question. Let I have class Cat. Cat has age attribute, which is Class::Integer. How can I add method .humanize, which will calculate human age equivalent form all cats in my project? i.e. ...

我有一些Ruby问题。让我上课。 Cat具有age属性,即Class :: Integer。如何添加方法.humanize,它将计算我项目中所有猫的人类年龄等值?即......

@cat.age #=> 2
@cat.age.humanize #=> 20
@tree.age #=> 5
@tree.age.humanize #=> NO METHOD ERROR!!! OH, YEAH!

1 个解决方案

#1


1  

This is called metaprogramming. You can accomplish what you want by doing the following:

这称为元编程。您可以通过执行以下操作来完成您想要的任务:

def @cat.humanize_age
  return @age * 10
end

You could add the method onto the Integer class from within Cat itself:

您可以在Cat本身内将该方法添加到Integer类中:

class Cat
  attr_accessor :age

  def initialize(a)
    @age = a
    add_meta
  end

  def add_meta
    def @age.humanize
      return self * 10
    end
  end
end

#1


1  

This is called metaprogramming. You can accomplish what you want by doing the following:

这称为元编程。您可以通过执行以下操作来完成您想要的任务:

def @cat.humanize_age
  return @age * 10
end

You could add the method onto the Integer class from within Cat itself:

您可以在Cat本身内将该方法添加到Integer类中:

class Cat
  attr_accessor :age

  def initialize(a)
    @age = a
    add_meta
  end

  def add_meta
    def @age.humanize
      return self * 10
    end
  end
end