模块实例方法变成类方法

Module MyMod
   def meth3
      puts "Module instance method meth3"
      puts "can become a class method."
   end
end

class MyClass
   class << self     #Here, self is MyClass
      include MyMod
   end
end
MyClass.meth3
# Output:
#   Module instance method meth3
#   can become a class method.

在这里方法extend很有用,这样类定义将变成:

class MyClass
   extend MyMod
end

使用extend例子

module Quantifier
  def any?
     self.each{|x|  return true if yield x}
  end

  def all?
     self.each{|x| return true if not yield x}
  end
end
list = [1,2,3,4,5]
list.extend(Quantifier)
flasg1=list.any?{|x| x>5  }   #false
flasg1=list.any?{|x| x>=5}   #true

flasg1=list.all?{|x| x<= 10}   #true
flasg1=list.all?{|x| x%2 == 0}   #false

方法any?与all?被混合插入到数组list中。

Comments