IceDragon200

[ruby]Array#gather

May 28th, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.78 KB | None | 0 0
  1. #
  2. # Challenge/Array_gather.rb
  3. #   by IceDragon
  4. #   dc 28/05/2013
  5. #   dm 28/05/2013
  6. # vr 1.0.0
  7. # Aim: Write an Array method which groups elements based on condition
  8. # EG. if an array [1,2,3,4,1,3,5,6,7,4,1,9,0] was given
  9. #     it'd return [1,1,1],[2],[3,3],[4,4],[5],[6],[7],[9],[0]
  10. # Completion Time: 30 Minutes
  11. array = [1,2,3,4,1,3,5,6,7,4,1,9,0]
  12.  
  13. module Enumerable
  14.  
  15.   ##
  16.   # group_by { |a, b| condition_for_grouping }
  17.   def group_by
  18.     result = []
  19.     src = dup
  20.     while (x = src.shift)
  21.       result.push((a = []).push(x))
  22.       src.reject! { |y| (a.push(y); true) if yield(x, y) }
  23.     end
  24.     return result
  25.   end
  26.  
  27.   ##
  28.   # gather
  29.   def gather(&block)
  30.     sort.group_by(&(block || (->(a, b){ a == b })))
  31.   end
  32.  
  33. end
  34.  
  35. if $0 == __FILE__
  36.   p array.gather
  37. end
Advertisement
Add Comment
Please, Sign In to add comment