Code tagged with enumerable

Paginating an Array/Enumerable

  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options

    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end
Language Ruby / Tagged with pagination, array, enumerable

Enumerable#count extension

# Often times i’m looking for how many Ns I have in an enumerated set (such as 
# an Array). This little extension of module Enumerable does the trick:

module Enumerable
   def count(what)
     self.inject(0) { |a,b| a += 1 if b == what;a 
   end
end

# Usage
irb(main):070:0> f = [1,2,3,3,4,44,5,55,3,54,2,2,54,6,6,3423,2,4,6,1]
=> [1, 2, 3, 3, 4, 44, 5, 55, 3, 54, 2, 2, 54, 6, 6, 3423, 2, 4, 6, 1]
irb(main):071:0> f.count(2)
=> 4
Language Ruby / Tagged with enumerable