chandradot99
chandradot99

Reputation: 3876

how to declare functions in module in ruby

In the below code, what is the difference between declaring two methods differently. Second method is declared using Week but first method is declared without using Week. And we are also not able to access second method by the class object d1. It gives the error

undefined method `weeks_in_year' for #<Decade:0x2c08a28> (NoMethodError)

then what is the use of declaring methods using Week prefix in second method when it is of no use.

module Week
   def 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

class Decade
   include Week
end

d1=Decade.new
d1.weeks_in_month
d1.weeks_in_year

Upvotes: 3

Views: 132

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

The way you have defined the method weeks_in_year is a class method of the Week class, not an instance method. That's why it didn't get inherited and you got the error as you posted.

You can use module_function to use the same method as a class method or instance method.

module Week
  def weeks_in_month
    puts "You have four weeks in a month"
  end

  def weeks_in_year
    puts "You have 52 weeks in a year"
  end

  module_function :weeks_in_year
end

class Decade
  include Week

  def wrapper_of_weeks_in_year
    weeks_in_year
  end
end

d1 = Decade.new

d1.weeks_in_month
# You have four weeks in a month
d1.wrapper_of_weeks_in_year
# You have 52 weeks in a year
Week.weeks_in_year
# You have 52 weeks in a year

While you will be using module_function, The instance-method versions are made private. That's why you need to use a wrapper method to call it as direct invocation is not possible.

Upvotes: 2

Related Questions