Mega Code Archive

 
Categories / Ruby / Class
 

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