Use extend to include a module to create single methods : singleton method « Class « Ruby






Use extend to include a module to create single methods


module Quantifier

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

  def all?
    self.each { |x| return false if not yield x }
    true
  end

end


list = [1, 2, 3, 4, 5]


list.extend(Quantifier)

flag1 = list.any? {|x| x > 5 }        # false
flag2 = list.any? {|x| x >= 5 }       # true
flag3 = list.all? {|x| x <= 10 }      # true
flag4 = list.all? {|x| x % 2 == 0 }   # false

 








Related examples in the same category

1.Add singleton method to a string instance
2.Add a singleton method to a instance object
3.Singleton method not copied