4 # ary.uniq! -> ary or nil
5 # ary.uniq! { |item| ... } -> ary or nil
7 # Removes duplicate elements from +self+.
8 # Returns <code>nil</code> if no changes are made (that is, no
9 # duplicates are found).
11 # a = [ "a", "a", "b", "b", "c" ]
12 # a.uniq! #=> ["a", "b", "c"]
13 # b = [ "a", "b", "c" ]
15 # c = [["student","sam"], ["student","george"], ["teacher","matz"]]
16 # c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
23 hash[key] = val unless hash.key?(key)
33 if result.size == self.size
43 # ary.uniq { |item| ... } -> new_ary
45 # Returns a new array by removing duplicate values in +self+.
47 # a = [ "a", "a", "b", "b", "c" ]
48 # a.uniq #=> ["a", "b", "c"]
50 # b = [["student","sam"], ["student","george"], ["teacher","matz"]]
51 # b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
61 # ary - other_ary -> new_ary
63 # Array Difference---Returns a new array that is a copy of
64 # the original array, removing any items that also appear in
65 # <i>other_ary</i>. (If you need set-like behavior, see the
68 # [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
71 raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
78 hash[elem[idx]] = true
85 array << v unless hash[v]
93 # ary | other_ary -> new_ary
95 # Set Union---Returns a new array by joining this array with
96 # <i>other_ary</i>, removing duplicates.
98 # [ "a", "b", "c" ] | [ "c", "d", "a" ]
99 # #=> [ "a", "b", "c", "d" ]
102 raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
110 # ary.union(other_ary,...) -> new_ary
112 # Set Union---Returns a new array by joining this array with
113 # <i>other_ary</i>, removing duplicates.
115 # ["a", "b", "c"].union(["c", "d", "a"], ["a", "c", "e"])
116 # #=> ["a", "b", "c", "d", "e"]
129 # ary & other_ary -> new_ary
131 # Set Intersection---Returns a new array
132 # containing elements common to the two arrays, with no duplicates.
134 # [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
137 raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
144 hash[elem[idx]] = true
162 # ary.flatten -> new_ary
163 # ary.flatten(level) -> new_ary
165 # Returns a new array that is a one-dimensional flattening of this
166 # array (recursively). That is, for every element that is an array,
167 # extract its elements into the new array. If the optional
168 # <i>level</i> argument determines the level of recursion to flatten.
170 # s = [ 1, 2, 3 ] #=> [1, 2, 3]
171 # t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
172 # a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
173 # a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
174 # a = [ 1, 2, [3, [4, 5] ] ]
175 # a.flatten(1) #=> [1, 2, 3, [4, 5]]
177 def flatten(depth=nil)
185 # ary.flatten! -> ary or nil
186 # ary.flatten!(level) -> array or nil
188 # Flattens +self+ in place.
189 # Returns <code>nil</code> if no modifications were made (i.e.,
190 # <i>ary</i> contains no subarrays.) If the optional <i>level</i>
191 # argument determines the level of recursion to flatten.
193 # a = [ 1, 2, [3, [4, 5] ] ]
194 # a.flatten! #=> [1, 2, 3, 4, 5]
196 # a #=> [1, 2, 3, 4, 5]
197 # a = [ 1, 2, [3, [4, 5] ] ]
198 # a.flatten!(1) #=> [1, 2, 3, [4, 5]]
200 def flatten!(depth=nil)
207 if e.is_a?(Array) && (depth.nil? || depth > 0)
208 ar += e.flatten(depth.nil? ? nil : depth - 1)
224 # ary.compact -> new_ary
226 # Returns a copy of +self+ with all +nil+ elements removed.
228 # [ "a", nil, "b", nil, "c", nil ].compact
229 # #=> [ "a", "b", "c" ]
239 # ary.compact! -> ary or nil
241 # Removes +nil+ elements from the array.
242 # Returns +nil+ if no changes were made, otherwise returns
245 # [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
246 # [ "a", "b", "c" ].compact! #=> nil
249 result = self.select { |e| !e.nil? }
250 if result.size == self.size
258 def reverse_each(&block)
259 return to_enum :reverse_each unless block
271 # ary.fetch(index) -> obj
272 # ary.fetch(index, default) -> obj
273 # ary.fetch(index) { |index| block } -> obj
275 # Tries to return the element at position +index+, but throws an IndexError
276 # exception if the referenced +index+ lies outside of the array bounds. This
277 # error can be prevented by supplying a second argument, which will act as a
280 # Alternatively, if a block is given it will only be executed when an
281 # invalid +index+ is referenced.
283 # Negative values of +index+ count from the end of the array.
285 # a = [ 11, 22, 33, 44 ]
288 # a.fetch(4, 'cat') #=> "cat"
289 # a.fetch(100) { |i| puts "#{i} is out of bounds" }
290 # #=> "100 is out of bounds"
293 def fetch(n, ifnone=NONE, &block)
294 warn "block supersedes default value argument" if !n.nil? && ifnone != NONE && block
300 if idx < 0 || size <= idx
301 return block.call(n) if block
303 raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
312 # ary.fill(obj) -> ary
313 # ary.fill(obj, start [, length]) -> ary
314 # ary.fill(obj, range ) -> ary
315 # ary.fill { |index| block } -> ary
316 # ary.fill(start [, length] ) { |index| block } -> ary
317 # ary.fill(range) { |index| block } -> ary
319 # The first three forms set the selected elements of +self+ (which
320 # may be the entire array) to +obj+.
322 # A +start+ of +nil+ is equivalent to zero.
324 # A +length+ of +nil+ is equivalent to the length of the array.
326 # The last three forms fill the array with the value of the given block,
327 # which is passed the absolute index of each element to be filled.
329 # Negative values of +start+ count from the end of the array, where +-1+ is
332 # a = [ "a", "b", "c", "d" ]
333 # a.fill("x") #=> ["x", "x", "x", "x"]
334 # a.fill("w", -1) #=> ["x", "x", "x", "w"]
335 # a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
336 # a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
337 # a.fill { |i| i*i } #=> [0, 1, 4, 9]
338 # a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
339 # a.fill(1, 2) { |i| i+1 } #=> [0, 2, 3, 27]
340 # a.fill(0..1) { |i| i+1 } #=> [1, 2, 3, 27]
343 def fill(arg0=nil, arg1=nil, arg2=nil, &block)
344 if arg0.nil? && arg1.nil? && arg2.nil? && !block
345 raise ArgumentError, "wrong number of arguments (0 for 1..3)"
351 if arg0.nil? && arg1.nil? && arg2.nil?
352 # ary.fill { |index| block } -> ary
355 elsif !arg0.nil? && arg0.kind_of?(Range)
356 # ary.fill(range) { |index| block } -> ary
358 beg += self.size if beg < 0
360 len += self.size if len < 0
361 len += 1 unless arg0.exclude_end?
363 # ary.fill(start [, length] ) { |index| block } -> ary
365 beg += self.size if beg < 0
373 if !arg0.nil? && arg1.nil? && arg2.nil?
374 # ary.fill(obj) -> ary
377 elsif !arg0.nil? && !arg1.nil? && arg1.kind_of?(Range)
378 # ary.fill(obj, range ) -> ary
380 beg += self.size if beg < 0
382 len += self.size if len < 0
383 len += 1 unless arg1.exclude_end?
384 elsif !arg0.nil? && !arg1.nil?
385 # ary.fill(obj, start [, length]) -> ary
387 beg += self.size if beg < 0
399 self[i] = block.call(i)
413 # ary.rotate(count=1) -> new_ary
415 # Returns a new array by rotating +self+ so that the element at +count+ is
416 # the first element of the new array.
418 # If +count+ is negative then it rotates in the opposite direction, starting
419 # from the end of +self+ where +-1+ is the last element.
421 # a = [ "a", "b", "c", "d" ]
422 # a.rotate #=> ["b", "c", "d", "a"]
423 # a #=> ["a", "b", "c", "d"]
424 # a.rotate(2) #=> ["c", "d", "a", "b"]
425 # a.rotate(-3) #=> ["b", "c", "d", "a"]
432 idx = (count < 0) ? (len - (~count % len) - 1) : (count % len) # rotate count
436 idx = 0 if idx > len-1
444 # ary.rotate!(count=1) -> ary
446 # Rotates +self+ in place so that the element at +count+ comes first, and
449 # If +count+ is negative then it rotates in the opposite direction, starting
450 # from the end of the array where +-1+ is the last element.
452 # a = [ "a", "b", "c", "d" ]
453 # a.rotate! #=> ["b", "c", "d", "a"]
454 # a #=> ["b", "c", "d", "a"]
455 # a.rotate!(2) #=> ["d", "a", "b", "c"]
456 # a.rotate!(-3) #=> ["a", "b", "c", "d"]
459 self.replace(self.rotate(count))
464 # ary.delete_if { |item| block } -> ary
465 # ary.delete_if -> Enumerator
467 # Deletes every element of +self+ for which block evaluates to +true+.
469 # The array is changed instantly every time the block is called, not after
470 # the iteration is over.
472 # See also Array#reject!
474 # If no block is given, an Enumerator is returned instead.
476 # scores = [ 97, 42, 75 ]
477 # scores.delete_if {|score| score < 80 } #=> [97]
479 def delete_if(&block)
480 return to_enum :delete_if unless block
483 while idx < self.size do
484 if block.call(self[idx])
495 # ary.reject! { |item| block } -> ary or nil
496 # ary.reject! -> Enumerator
498 # Equivalent to Array#delete_if, deleting elements from +self+ for which the
499 # block evaluates to +true+, but returns +nil+ if no changes were made.
501 # The array is changed instantly every time the block is called, not after
502 # the iteration is over.
504 # See also Enumerable#reject and Array#delete_if.
506 # If no block is given, an Enumerator is returned instead.
509 return to_enum :reject! unless block
513 while idx < self.size do
514 if block.call(self[idx])
529 # ary.insert(index, obj...) -> ary
531 # Inserts the given values before the element with the given +index+.
533 # Negative indices count backwards from the end of the array, where +-1+ is
537 # a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
538 # a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
540 def insert(idx, *args)
541 idx += self.size + 1 if idx < 0
548 # ary.bsearch {|x| block } -> elem
550 # By using binary search, finds a value from this array which meets
551 # the given condition in O(log n) where n is the size of the array.
553 # You can use this method in two use cases: a find-minimum mode and
554 # a find-any mode. In either case, the elements of the array must be
555 # monotone (or sorted) with respect to the block.
557 # In find-minimum mode (this is a good choice for typical use case),
558 # the block must return true or false, and there must be an index i
559 # (0 <= i <= ary.size) so that:
561 # - the block returns false for any element whose index is less than
563 # - the block returns true for any element whose index is greater
564 # than or equal to i.
566 # This method returns the i-th element. If i is equal to ary.size,
569 # ary = [0, 4, 7, 10, 12]
570 # ary.bsearch {|x| x >= 4 } #=> 4
571 # ary.bsearch {|x| x >= 6 } #=> 7
572 # ary.bsearch {|x| x >= -1 } #=> 0
573 # ary.bsearch {|x| x >= 100 } #=> nil
575 # In find-any mode (this behaves like libc's bsearch(3)), the block
576 # must return a number, and there must be two indices i and j
577 # (0 <= i <= j <= ary.size) so that:
579 # - the block returns a positive number for ary[k] if 0 <= k < i,
580 # - the block returns zero for ary[k] if i <= k < j, and
581 # - the block returns a negative number for ary[k] if
584 # Under this condition, this method returns any element whose index
585 # is within i...j. If i is equal to j (i.e., there is no element
586 # that satisfies the block), this method returns nil.
588 # ary = [0, 4, 7, 10, 12]
589 # # try to find v such that 4 <= v < 8
590 # ary.bsearch {|x| 1 - (x / 4).truncate } #=> 4 or 7
591 # # try to find v such that 8 <= v < 10
592 # ary.bsearch {|x| 4 - (x / 2).truncate } #=> nil
594 # You must not mix the two modes at a time; the block must always
595 # return either true/false, or always return a number. It is
596 # undefined which value is actually picked up at each iteration.
599 return to_enum :bsearch unless block
601 if idx = bsearch_index(&block)
610 # ary.bsearch_index {|x| block } -> int or nil
612 # By using binary search, finds an index of a value from this array which
613 # meets the given condition in O(log n) where n is the size of the array.
615 # It supports two modes, depending on the nature of the block and they are
616 # exactly the same as in the case of #bsearch method with the only difference
617 # being that this method returns the index of the element instead of the
618 # element itself. For more details consult the documentation for #bsearch.
620 def bsearch_index(&block)
621 return to_enum :bsearch_index unless block
628 mid = ((low+high)/2).truncate
629 res = block.call self[mid]
632 when 0 # find-any mode: Found!
634 when Numeric # find-any mode: Continue...
635 in_lower_half = res < 0
636 when true # find-min mode
639 when false, nil # find-min mode
640 in_lower_half = false
642 raise TypeError, 'invalid block result (must be numeric, true, false or nil)'
652 satisfied ? low : nil
657 # ary.delete_if { |item| block } -> ary
658 # ary.delete_if -> Enumerator
660 # Deletes every element of +self+ for which block evaluates to +true+.
662 # The array is changed instantly every time the block is called, not after
663 # the iteration is over.
665 # See also Array#reject!
667 # If no block is given, an Enumerator is returned instead.
669 # scores = [ 97, 42, 75 ]
670 # scores.delete_if {|score| score < 80 } #=> [97]
672 def delete_if(&block)
673 return to_enum :delete_if unless block
676 while idx < self.size do
677 if block.call(self[idx])
688 # ary.keep_if { |item| block } -> ary
689 # ary.keep_if -> Enumerator
691 # Deletes every element of +self+ for which the given block evaluates to
694 # See also Array#select!
696 # If no block is given, an Enumerator is returned instead.
698 # a = [1, 2, 3, 4, 5]
699 # a.keep_if { |val| val > 3 } #=> [4, 5]
702 return to_enum :keep_if unless block
706 while idx < self.size do
707 if block.call(self[idx])
718 # ary.select! {|item| block } -> ary or nil
719 # ary.select! -> Enumerator
721 # Invokes the given block passing in successive elements from +self+,
722 # deleting elements for which the block returns a +false+ value.
724 # If changes were made, it will return +self+, otherwise it returns +nil+.
726 # See also Array#keep_if
728 # If no block is given, an Enumerator is returned instead.
731 return to_enum :select! unless block
738 result << elem if block.call(elem)
741 return nil if len == result.size
747 # ary.index(val) -> int or nil
748 # ary.index {|item| block } -> int or nil
750 # Returns the _index_ of the first object in +ary+ such that the object is
751 # <code>==</code> to +obj+.
753 # If a block is given instead of an argument, returns the _index_ of the
754 # first object for which the block returns +true+. Returns +nil+ if no
758 def index(val=NONE, &block)
759 return to_enum(:find_index, val) if !block && val == NONE
765 return idx if block.call self[idx]
769 return self.__ary_index(val)
776 # ary.dig(idx, ...) -> object
778 # Extracts the nested value specified by the sequence of <i>idx</i>
779 # objects by calling +dig+ at each step, returning +nil+ if any
780 # intermediate step is +nil+.
793 # ary.permutation { |p| block } -> ary
794 # ary.permutation -> Enumerator
795 # ary.permutation(n) { |p| block } -> ary
796 # ary.permutation(n) -> Enumerator
798 # When invoked with a block, yield all permutations of length +n+ of the
799 # elements of the array, then return the array itself.
801 # If +n+ is not specified, yield all permutations of all elements.
803 # The implementation makes no guarantees about the order in which the
804 # permutations are yielded.
806 # If no block is given, an Enumerator is returned instead.
811 # a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
812 # a.permutation(1).to_a #=> [[1],[2],[3]]
813 # a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
814 # a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
815 # a.permutation(0).to_a #=> [[]] # one permutation of length 0
816 # a.permutation(4).to_a #=> [] # no permutations of length 4
817 def permutation(n=self.size, &block)
819 return to_enum(:permutation, n) unless block
828 ary = self[0...i] + self[i+1..-1]
829 ary.permutation(n-1) do |c|
842 # ary.combination(n) { |c| block } -> ary
843 # ary.combination(n) -> Enumerator
845 # When invoked with a block, yields all combinations of length +n+ of elements
846 # from the array and then returns the array itself.
848 # The implementation makes no guarantees about the order in which the
849 # combinations are yielded.
851 # If no block is given, an Enumerator is returned instead.
856 # a.combination(1).to_a #=> [[1],[2],[3],[4]]
857 # a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
858 # a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
859 # a.combination(4).to_a #=> [[1,2,3,4]]
860 # a.combination(0).to_a #=> [[]] # one combination of length 0
861 # a.combination(5).to_a #=> [] # no combinations of length 5
863 def combination(n, &block)
865 return to_enum(:combination, n) unless block
879 self[i+1..-1].combination(n-1) do |c|
889 # ary.transpose -> new_ary
891 # Assumes that self is an array of arrays and transposes the rows and columns.
893 # If the length of the subarrays don't match, an IndexError is raised.
897 # a = [[1,2], [3,4], [5,6]]
898 # a.transpose #=> [[1, 3, 5], [2, 4, 6]]
905 raise TypeError unless row.is_a?(Array)
906 column_count ||= row.count
907 raise IndexError, 'element size differs' unless column_count == row.count
910 Array.new(column_count) do |column_index|
911 self.map { |row| row[column_index] }
918 # ary.to_h{|item| ... } -> Hash
920 # Returns the result of interpreting <i>aray</i> as an array of
921 # <tt>[key, value]</tt> pairs. If a block is given, it should
922 # return <tt>[key, value]</tt> pairs to construct a hash.
924 # [[:foo, :bar], [1, 2]].to_h
925 # # => {:foo => :bar, 1 => 2}
926 # [1, 2].to_h{|x| [x, x*2]}
927 # # => {1 => 2, 2 => 4}
932 v = blk.call(v) if blk
933 raise TypeError, "wrong element type #{v.class}" unless Array === v
934 raise ArgumentError, "wrong array length (expected 2, was #{v.length})" unless v.length == 2