public
Description: Collective Idea's Awesomeness. A collection of useful Rails bits and pieces.
Homepage:
Clone URL: git://github.com/collectiveidea/awesomeness.git
Click here to lend your support to: awesomeness and make a donation at www.pledgie.com !
awesomeness / lib / awesomeness / core_ext / array.rb
100644 39 lines (32 sloc) 0.807 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Array
  
  def randomize(limit = length)
    choices = dup
    returning([]) do |result|
      [limit, length].min.times do
        result << choices.delete_at(Kernel.rand(choices.length))
      end
    end.compact
  end
  
  def uniq_with_block!(&block)
    uniq_without_block!
    if block_given?
      grouped = group_by(&block)
      grouped.each do |key,duplicates|
        delete_at(index(duplicates.pop)) while duplicates.size > 1
      end
    end
    self
  end
  alias_method_chain :uniq!, :block
  
  def uniq_with_block(&block)
    dup.uniq!(&block)
  end
  alias_method_chain :uniq, :block
  
  def pad(pad_to_length, padding = nil)
    dup.pad! pad_to_length, padding
  end
  
  def pad!(pad_to_length, padding = nil)
    self << padding while pad_to_length > length
    self
  end
 
end