[英]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
. 第二种方法是使用Week
声明的,但是声明第一种方法而不使用Week
。 And we are also not able to access second method by the class object d1
. 而且我们也无法通过类对象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. 那么当它没用时,在第二种方法中使用Week
前缀声明方法的用途是什么。
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
The way you have defined the method weeks_in_year
is a class method of the Week
class, not an instance method. 您定义方法的方式weeks_in_year
是Week
类的类方法,而不是实例方法。 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_function
使用与类方法或实例方法相同的方法。
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 . 当您将使用module_function
, 实例方法版本将变为私有 。 That's why you need to use a wrapper method to call it as direct invocation is not possible. 这就是为什么你需要使用包装器方法来调用它,因为直接调用是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.