Writing Block Methods that Classify or Collect : Enumerable « Collections « Ruby






Writing Block Methods that Classify or Collect


module Enumerable
  def find_no_more_than(limit)
    inject([]) do |a,e|
      a << e if yield e
      return a if a.size >= limit
      a
    end
  end
end

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.find_no_more_than(3) { |x| x % 2 == 0 }            # => [2, 4, 6]

 








Related examples in the same category

1.get Enumerable involved
2.Sorting an Array by Frequency of Appearance
3.Add cartesian to Enumerable
4.Building a Histogram
5.Call each a number of times
6.randomly each
7.Implementing Enumerable - Write One Method, Get 22 Free
8.Enumerable.instance_methods.sort
9.Sort on two arrays