Wednesday, November 5, 2014

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

3:32 PM



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:

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy