ruby-on-railsrubyfunctionoopnomethoderror

I keep getting this error and i can't seem to fix it


I keep on getting
in `eater': undefined method `hunger' for Human:Class (NoMethodError)

and this is the code i wrote :

   class Human
    attr_reader :name, :age, :hunger
    def initialize(name,age);
        @name = name
        @age = age
        @hunger = 50
    end 
    def eater() ;
        Human.hunger -= 10          
    end 
end

person = Human.new('Josh',32)
puts person.eater  

basically i want to decrease the hunger of the person by 10 and then print the current amount of hunger but instead of printing it it keeps on giving me this error, I kind of used the concepts of OOP from python but even that doesn't seem to work, I have tried almost everything and spent hours trying to get this can someone please help


Solution

  • I think this is what you want to do:

    class Human
      attr_reader :name, :age, :hunger
    
      def initialize(name, age, hunger = 50)
        @name = name
        @age = age
        @hunger = hunger
      end
    
      def eater
        @hunger -= 10
      end
    end
    
    person = Human.new('Josh', 32)
    puts person.eater
    
    

    Unless you want @hunger to always be 50 for all objects and not changed.

    Don't set a default value as an instance variable on the object like you're doing with @hunger = 50. Instead, you want that default value to be in the parameters.

    Also this Human.hunger -= 10 should be @hunger -= 10 because I'm assuming when you call #eater on the object you want it to decrement by 10.

    It appears you're not using any of the methods attr_reader :name, :age, :hunger gives you, you might as well get rid of that line as attr_reader :name is just a shortcut to:

    def name
      @name
    end