#-- # EnumerableArgs # # Copyright (c) 2004,2005 Thomas Sawyer # # Ruby License # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. # # # ========================================================================== # Revision History :: # -------------------------------------------------------------------------- # 04.06 Trans * Minor modifications to documentation. # ========================================================================== # # :NOTE: The #sort method still needs to be done. # #++ #:title: EnumerableArgs # # This is a simple reimplementation of the core Enumerable module # to allow the methods to take and pass-on arbitrary arguments to the # underlying #each call. # # == Synopsis # # require 'enumerable_args' # # class T # include EnumerableArgs # def initialize(arr) # @arr = arr # end # def each(n) # arr.each{ |e| yield(e+n) } # end # end # # t = T.new([1,2,3]) # t.collect(4) # #=> [5,6,7] # # == Author(s) # # Thomas Sawyer # module EnumerableArgs VERSION = '0.9.0' def collect(*args) # :yield: a = [] each(*args){ |n| a << yield(n) } a end alias_method( :map, :collect ) def detect(*args) # :yield: each(*args){ |n| return n if yield(n) } nil end alias_method( :find, :detect ) # problematic for multiple arity on block #def each_with_index(*args) # i=0 # each(*args){ |n,i| yield(n); i+=1 } # self #end def to_a(*args) a = [] each(*args){ |n| a << n } a end alias_method( :entries, :to_a ) # An additional method not part of standard Enumerable. # The regular version of this method can be found in Facets, # but it is a bit more advanced then this one. # At some point they need to be put into sync. def each_slice(*args, &yld) a = []; s = [] ar = yld.arity.abs each(*args){ |n| s << n if s.length >= ar yld.call(*s) s = [] end } a end alias_method( :each_by, :each_slice ) def select(*args) # :yield: a = [] each(*args){ |n| a << n if yield(n) } a end alias_method( :find_all, :select ) def grep(pattern, *args) a = [] each(*args){ |n| a << (block_given? ? yield(n) : n) if pattern === n } a end def include?(anObj, *args) each(*args){ |n| return true if anObj == n } false end alias_method( :member?, :include? ) def max(*args) to_a(*args).max end def min(*args) to_a(*args).min end def reject(*args) a = [] each(*args){ |n| a << n if ! yield(n) } a end def sort(*args) # TODO end end