0

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. ...

@cat.age #=> 2
@cat.age.humanize #=> 20
@tree.age #=> 5
@tree.age.humanize #=> NO METHOD ERROR!!! OH, YEAH!
1
  • 1
    @everm1ind, folks will shun your questions if you never accept answers. You should go through all the answers you've been given for each question, and click the check mark next to the most helpful ones if you want to be taken seriously on StackOverflow. Commented Sep 28, 2011 at 18:43

1 Answer 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:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.