Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a module from another file

Tags:

ruby

I am attempting to call a module into the main script. I linked the files using require. The following is what my code looks like:

module Ex36_method
    def m_defense
        puts "Do you want to play zone or man to man for this possession?"
        print "> "
        choice = $stdin.gets.chomp
        if choice.include? "zone"
            zone
        elsif choice.include? "man to man"
            m_rebound
        else
            dead("You failed to play defense")
        end
    end
    def zone
        puts "The opposition scores a 3!"
    end
    def m_rebound
        puts "The ball rims out and you got a rebound!"
    end
end

require_relative 'Ex36_method' 

def start 
    puts "You are in the final minute of game 7 of the NBA finals."
    puts "You are down by 3 points."
    puts "What do you do: take a 3 pointer that might tie or take a guaranteed 2?"
    print "> "
    choice = $stdin.gets.chomp
    if choice.include? "3 pointer"
        puts "You missed! The ball rims out but you got the rebound at 40 seconds."
        pass 
    elsif choice.include? "2 pointer"
        puts "You scored! 50 seconds on the clock. Now it's time for defense"
        m_rebound
    else
        dead("Turnover")
    end
end
def dead(why)
    puts why, "The opposing team scores a 3 and you lose. Better luck next year!"
end
start

When I call the functions in the linked module, I receive the following error:

"ex36.rb:16:in `start': undefined local variable or method `m_rebound' for main:Object (NameError)
    from ex36.rb:27:in `<main>'"

Any help would be much appreciated.

like image 531
Karthik Soravanahalli Avatar asked Feb 16 '15 23:02

Karthik Soravanahalli


2 Answers

You have loaded the module, but have not yet included the module's methods into the current scope. Add an include statement:

require_relative 'Ex36_method'

include Ex36_method

def start
#...
like image 98
Mori Avatar answered Oct 11 '22 11:10

Mori


This shows how qualifying the method with it's class desciptor using the "::" prefix allows the interpreter's linkage code to resolve the reference.

#animal.rb

module Animals
    def hello
        puts "hello dear"
    end
end


#index.rb

require_relative "animal"

include Animals

Animals::hello #ouputs "hello dear"
like image 35
Atiene Jonathan Avatar answered Oct 11 '22 12:10

Atiene Jonathan