Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, November 5, 2014

In Ruby how to use the function of a module defined in a different directory



To use the function of a module defined in a different directory below steps need to be followed.

1. Define a module in some directory other then which have your ruby class.

Example

Say some module Week is defined in trig.rb file inside io/test package.


module Week
  FIRST_DAY = "Sunday"
  def Week.weeks_in_month
    puts "You have four weeks in a month"
  end
  def Week.weeks_in_year
    puts "You have 52 weeks in a year"
  end
end


2. To use this module related function in your class 'test.rb' use the below syntax.


#!/usr/bin/ruby

require_relative 'io/test/trig'

class Decade

end
d1=Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year

To make it more clear check the below the hierarchy diagram of directory structure.

Hierarchy diagram of above explanation


To download the above example code:

No comments: