Home > OS >  Undefined Method for Ruby Module
Undefined Method for Ruby Module

Time:05-22

I'm new to Ruby and programming in general and I'm working on a few practice projects. I have a module for my game that checks to see if my virtual pet is hungry.

module Reaction
  
  def hungry?
    if @dragon.hunger > 1
      @dragon.hunger -= 1
      print 'Mmmmmmm, thanks for the people parts!'
    else
      print 'I\'m full already!'
    end
  end

Then on my game file I have a class called StartGame.

require_relative 'dragon'
require_relative 'reaction'

class StartGame
  include Reaction
  attr_reader :dragon

I'm then attempting to use the module within my user_input method to check if the pet is already hungry.

 def user_input
    print "How would you like to interact with your dragon?\n"
    print "Feed, Sleep, Play, Pet, or Quit\n"
    print "Input:\n"
    @user_input = gets.capitalize.chomp
 if @user_input == 'Feed'
   Reaction.hungry?
 end

I seem to continuously get this error "undefined method `hungry?' for Reaction:Module (NoMethodError)"

The code within the module works perfectly when used like this

if @user_input == 'Feed'
    if @dragon.hunger > 1
      @dragon.hunger -= 1
      print 'Mmmmmmm, thanks for the people parts!'
    else
      print 'I\'m full already!'
    end
  end

I'm just not certain what I'm doing wrong here to search google effectively how to get the method to be defined.

CodePudding user response:

You module really haven't this method because hungry? is instance method

You include it to StartGame, so you can call it on this class instance

start_game.hungry?

But it looks that it is not game method, but dragon's (for example you have other hungry monsters)

So you need rewrite method and include this module to dragon class and call it as @dragon.hungry?

Methods with question marks usually are used to return boolean (true or false)

CodePudding user response:

Reaction#hungry? is an instance method, you have to include Reaction module in a class to use it:

module Reaction
  def hungry?
    'yes'
  end
end

class StartGame
  include Reaction # include will add `hungry?` as an instance method 

  def user_input
    hungry? # method from Reaction module
  end
end
>> StartGame.new.hungry?
=> yes
>> StartGame.new.user_input
=> yes

and

class Dragon
  include Reaction
end

# Dragon.new.hungry? # => 'yes'
  • Related