Sha256: ce9f99835bc3fd03b04bb3c552a09c82443e29b4e5f10700d91afac39160d6a4

Contents?: true

Size: 1.31 KB

Versions: 4

Compression:

Stored size: 1.31 KB

Contents

module Enumerable

  def search(not_found=nil)
    each do |x|
      val = yield(x)
      return val if val
    end
    not_found
  end

  def map_with_index
    res = []
    each_with_index {|x, i| res << yield(x, i)}
    res
  end
  
  def build_hash
    res = {}
    each do |x|
      pair = yield x
      res[pair.first] = pair.last if pair
    end
    res
  end
  
  def map_hash
    res = {}
    each do |x|
      v = yield x
      res[x] = v
    end
    res
  end
  
  def rest
    self[1..-1]
  end

  class MultiSender
 
    undef_method(*(instance_methods - %w*__id__ __send__*))

    def initialize(enumerable, method)
      @enumerable = enumerable
      @method     = method
    end

    def method_missing(name, *args, &block)
      @enumerable.send(@method) { |x| x.send(name, *args, &block) }
    end
    
  end
  
  def *()
    MultiSender.new(self, :map)
  end
  
  def where
    MultiSender.new(self, :select)
  end
  
  def where_not
    MultiSender.new(self, :reject)
  end
  
  def drop_while
    drop = 0
    drop += 1 while yield(self[drop])
    self[drop..-1] 
  end
  

  def take_while
    take = 0
    take += 1 while yield(self[take])
    self[0..take-1] 
  end

end


class Object

  def in?(enum)
    !enum.nil? && enum.include?(self)
  end

  def not_in?(enum)
    enum.nil? || !enum.include?(self)
  end
  
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
hobosupport-0.7.4 lib/hobosupport/enumerable.rb
hobosupport-0.2 lib/hobosupport/enumerable.rb
hobosupport-0.7.3.99 lib/hobosupport/enumerable.rb
hobosupport-0.7.5 lib/hobosupport/enumerable.rb