class NilClass
# Provide platform dependent null path. # # @standard # require 'facets/pathname' # # @author Daniel Burger def to_path Pathname.null end
end
empty? | -> | blank? |
shift | -> | pull |
Alias for shift which removes an object off first slot of an array. This is the opposite of pop. | ||
shift | -> | first! |
Alias for shift, which removes and returns the first element in an array.
a = ["a","y","z"] a.first! #=> "a" a #=> ["y","z"] CREDIT: Trans |
||
pop | -> | last! |
Alias for pop, which removes and returns the last element in an array.
a = [1,2,3] a.last! #=> 3 a #=> [1,2] CREDIT: Trans |
||
| | -> | merge |
Alias for |.
[1,2].merge([2,3]) #=> [1,2,3] |
||
[]= | -> | store |
Store a value at a given index. Store is an alias for #[]=.
Example: a = [] a.store(1, "A") a[1] #=> "A" Returns the stored object. |
||
include? | -> | contains? |
Alias for include?. | ||
each | -> | each_value |
Alias for each. The intention of this method is to provide polymorphism with Hash. | ||
product | -> | ** |
Array#** is an alias for Array#product.
NOTE: This method is not a common core extension and is not loaded automatically when using require ‘facets‘. @uncommon require 'facets/array/op_pow' |
The `arrange` method produces appropriate ranges from the objects in the array.
Examples
[1,2,3,6,7,8].arrange #=> [1..3, 6..8] [10..15, 16..20, 21, 22].arrange #=> [10..22]
Assumes inclusive ranges (ie. 1..4) and range.first <= range.last.
Works with integers, dates and strings. However, all the objects in the array must be of the same class.
CREDIT: monocle
Calculate the average of an array of numbers
Examples
[].average #=> nil [1, 2, 3].average #=> 2 [3, 12, 57, 85, 15, 89, 33, 7, 22, 54].average #=> 37.7 [1,[2,nil,[3]],nil,4].collapse #=> [1,2,3,4]
Returns the value previous to the given value. The value previous to the first is the last. Returns nil if the given value is not in the array.
Examples
sequence = ['a', 'b', 'c'] sequence.before('a') #=> 'c' sequence.before('b') #=> 'a' sequence.before('c') #=> 'b' sequence.before('d') #=> nil
CREDIT: Tyler Rick
Simplify an array by flattening it then compacting it.
Examples
[1,[2,nil,[3]],nil,4].collapse #=> [1,2,3,4]
Get a list of all items that have something in common in terms of the supplied block. If no block is given objects are considered to be in common if they return the same value for Object#hash and if obj1 == obj2.
This can be useful, for instance, in determining all persons that share their last name with another person.
persons.commonality { |person| person.last_name }
The method is similar to group_by which is a standard Ruby method as of 1.9. To get effectively the same results with group_by use `select{ |k,v| v.size > 1 }`.
[1, 2, 2, 3, 4, 4].group_by{ |e| e }.select{ |k,v| v.size > 1 } #=> { 2 => [2, 2], 4 => [4, 4] }
Examples
[1, 2, 2, 3, 4, 4].commonality #=> { 2 => [2, 2], 4 => [4, 4] } ["foo", "bar", "baz"].commonality { |str| str[0] } #=> { 'b' => ["bar", "baz"] }
Returns [Hash] mapping common attribute to those elements.
CREDIT: Florian Gross
This is more advanced form of join. It allows for fine control of separators.
NOTE: The old version used to default its separator to ", " and default the terminating separator to " and ". This is no longer the case. You must specifically provide these parameters.
If no paramters are given, it acts like join but will a space separator.
[1,2,3].conjoin #=> "1 2 3"
Use comma+space and ‘and’ on tail.
[1,2,3].conjoin(', ', ' and ') #=> "1, 2 and 3"
Use comma+space and ‘or’ on tail using :last option.
[1,2,3].conjoin(', ', :last => ' or ') #=> "1, 2 or 3"
Use semicolon+space and ampersand on tail using index.
[1,2,3].conjoin('; ', -1 => ' & ') #=> "1; 2 & 3"
Can take a block to determine separator.
[1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' } #=> "1.2-3.4"
This makes very esoteric transformation possible.
[1,1,2,2].conjoin{ |i, a, b| a == b ? '=' : ' != ' } #=> "1=1 != 2=2" [1,2,3,4].conjoin{ |i, x, y| "<#{i} #{x} #{y}>" } #=> "1<0 1 2>2<1 2 3>3<2 3 4>4"
There are also spacing options. Providing the :space option pads the separators.
[1,2,3].conjoin(',', '&', :space=>2) #=> "1 , 2 & 3"
And the :spacer option can set an alternate spacing string.
[1,2,3].conjoin('|', '>', :space=>2, :spacer=>'-') #=> "1--|--2-->--3"
CREDIT: Trans
Delete multiple values from array.
a = [1,2,3,4] a.delete_values(1,2) #=> [1,2] a #=> [3,4]
CREDIT: Trans
Delete multiple values from array given indexes or index range.
a = [1,2,3,4] a.delete_values_at(1,2) #=> [2,3] a #=> [1,4] a = [1,2,3,4] a.delete_values_at(0..2) #=> [1,2,3] a #=> [4]
NOTE: It would be nice to see delete_at incorporate this funcitonaility.
CREDIT: Trans
Divide on matching pattern.
['a1','b1','a2','b2'].divide(/^a/) #=> [['a1','b1'],['a2','b2']] ['a1','b1','a2','b2'].divide(/^b/) #=> [['a1',['b1','a2'],[]'b2']] ['a1','b1','a2','b2'].divide(/^c/) #=> [['a1','b1','a2','b2']]
CREDIT: Trans
Return list of duplicate elements.
min - The minimum number of duplication necessary for inclusion. [Integer]
Examples:
[1,1,2,3].duplicates #=> [1] [1,1,2,3,2,4,5,4,2].duplicates(3) #=> [2]
CREDIT: Rebort Dober (current implementation) CREDIT: Thibaut Barrère
Iterate over each slice where the last n values of a preceding slice overlap with the first n values of the following slice. The value of n is specified by the second `overlap` argument.
a, r = [1,2,3,4,5], [] a.each_overlap(2,1) { |x,y| r << [x,y] } r # => [[1,2],[2,3],[3,4],[4,5]]
Returns nothing.
Extracts options from a set of arguments. Removes and returns the last element in the array if it‘s a hash, otherwise returns a blank hash.
def options(*args) args.extract_options! end options(1, 2) # => {} options(1, 2, :a => :b) # => {:a=>:b}
Returns elements from `index` until the end.
%w{W o r l d}.from(3) #=> ["l", "d"] %w{W o r l d}.from(9) #=> []
Returns the maximum possible Shannon entropy of the array with given size assuming that it is an "order-0" source (each element is selected independently of the next).
CREDIT: Derek
Determines the sorted middle element.
a = %w{a a b b c c c} a.median #=> "b"
When there are an even number of elements, the greater of the two middle elements is given.
a = %w{a a b b c c c d} a.median #=> "c"
An offset can be supplied to get an element relative to the middle.
a = %w{a a b b c c c d} a.median(-1) #=> "b"
The the array is empty, nil is returned.
@return [Object] sorted middle element
Determine the "holes" in the values of an array.
TODO: Better name?
Returns the missing elements in an array set.
CREDIT: monocle
Returns a list of non-unique elements.
Examples
[1,1,2,2,3,4,5].nonuniq #=> [1,2]
CREDIT: Martin DeMello
Create a hash of each uniq element of the array and how many time each appears.
Examples
[:a,:a,:b,:c,:c,:c].occurrence #=> { :a => 2, :b => 1, :c => 3 } [2,2,3,4,4,4].occurrence{|i| i % 2} #=> { 0 => 5, 1 => 1 }
Returns the only element in the array. Raises an IndexError if the array‘s size is not 1.
[5].only # => 5 expect IndexError do [1,2,3].only end expect IndexError do [].only end
CREDIT: Gavin Sinclair, Noah Gibbs
Pad an array with a given value up to a given length.
[0,1,2].pad(6,"a") #=> [0,1,2,"a","a","a"]
If length is a negative number padding will be added to the beginning of the array.
[0,1,2].pad(-6,"a") #=> ["a","a","a",0,1,2]
CREDIT: Richard Laugesen
Like pad but changes the array in place.
a = [0,1,2] a.pad!(6,"x") a #=> [0,1,2,"x","x","x"]
CREDIT: Richard Laugesen
Peek at the top of the stack (the end of the array).
a = [1, 2, 3] a.peek #=> 3 a #=> [1, 2, 3]
Or provide an index to inspect the array from back to front.
Put an object on the bottom of the stack (front of the array).
a = [2, 3] a.poke(1) a #=> [1, 2, 3]
Or supply an index and poke works like insert.
Generates a hash mapping each unique element in the array to the relative frequency, i.e. the probability, of it appearance.
[:a, :b, :c, :c].probability #=> {:a=> 0.25, :b=>0.25, :c=>0.5}
CREDIT: Brian Schröder
Apply a block to array, and recursively apply that block to each sub-array or types.
arr = ["a", ["b", "c", nil], nil] arr.recurse{ |a| a.compact! } #=> ["a", ["b", "c"]]
Apply a method to array, and recursively apply that method to each sub-array or given types.
By default the sub-types are passed through unaffected. Passing a block to recursively can be used to change this.
types - List of class types to recurse. [Array<Class>] block - Optional filter procedure to apply on each recursion.
Examples
arr = ["a", ["b", "c"]] arr.recursively.map{ |v| v.to_sym } #=> [:a, [:b, :c]] arr = ["a", ["b", "c"]] arr.recursively{ |a| a.reverse }.map{ |v| v.to_sym } #=> [:a, [:c, :b]]
Returns [Recursor].
Non-destructive form of `Array#delete_values`. Unlike `delete_values` this method returns a new array.
values - List of array elements to reject.
Examples
[1,2,3,4,5].reject_values(2,4) # => [1,3,5]
Returns [Array]
CREDIT: Sean Mackesey
Convert an array into command line parameters. The array is accepted in the format of Ruby method arguments —ie. [arg1, arg2, …, hash]
Splice acts as a combination of slice! and store. If two arguments are given it calls store. If a single argument is given it calls slice!.
Examples
a = [1,2,3] a.splice(1) #=> 2 a #=> [1,3] a = [1,2,3] a.splice(1,4) #=> 4 a #=> [1,4,3]
Returns [Array].
CREDIT: Trans
Destructive version of Enumerable#squeeze.
a = [1,2,2,3,3,2,1] a.squeeze! a #=> [1,2,3,2,1] a = [1,2,2,3,3,2,1] a.squeeze!(*[3]) a #=> [1,2,2,3,2,1]
Returns the receiver. [Array]
CREDIT: T. Yamada
Calculate the standard_deviation of an array of numbers
Examples
[].standard_deviation #=> nil [1, 2, 3].standard_deviation #=> 0.816496580927726 [96, 35, 72, 30, 75, 33, 68, 13, 49, 71].standard_deviation #=> 24.69331893448104 [36, -67, -17, 85, -46, -64, -23, -13, 89, -47].standard_deviation #=> 54.67183918618432 [60.7829, 31.2622, 20.626, 78.8907, 61.5328].standard_deviation #=> 21.428815505053002
Iterate over every nth element of an array.
r = [] [:a, :b, :c, :d].step(2) { |x| r << x } r #=> [:b, :d]
Without a block it returns an Enumerator.
[:a, :b, :c, :d].step(1).to_a #=> [:a, :b, :c, :d] [:a, :b, :c, :d].step(2).to_a #=> [:b, :d] [:a, :b, :c, :d].step(3).to_a #=> [:c] [:a, :b, :c, :d].step(5).to_a #=> []
CREDIT: Ryan Duryea
Convert an associative array to a Hash.
Examples
[[:a, 1], [:b, 2]].to_h #=> {:a=>1, :b=>2}
Returns [Hash].
Construct a new array created by traversing the array and its sub-arrays, executing the given block on the elements.
Examples
h = ["A", "B", ["X", "Y"]] g = h.traverse{ |e| e.downcase } g #=> ["a", "b", ["x", "y"]]
This is the same as recursive.map and will likely be deprecated in the future because of it.
Returns new array. [Array]
CREDIT: Trans
Like recursive_map, but will change the array in place.
Examples:
h = ["A", "B", ["X", "Y"]] h.traverse!{ |e| e.downcase } h #=> ["a", "b", ["x", "y"]]
Returns self. [Array]
CREDIT: Trans
Like uniq, but determines uniqueness based on a given block. As can be seen in the following examples, order is significant.
Examples
a = (-5..5).to_a a.uniq_by!{ |i| i*i } a #=> [-5, -4, -3, -2, -1, 0] a = (-5..5).to_a.reverse a.uniq_by!{ |i| i*i } a #=> [5, 4, 3, 2, 1, 0]
Returns [Array] of unique elements.
Enumerates permutation of Array. Unlike Array#permutation, there are no duplicates in generated permutations. Instead, elements must be comparable.
[1,1,2,2,3].unique_permutation(2).to_a #=> [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2]] # Note: [1,1,2,2,3].permutation(2).to_a #=> [[1, 1], [1, 2], [1, 2], [1, 3], [1, 1], [1, 2], [1, 2], [1, 3], [2, 1], [2, 1], [2, 2], [2, 3], [2, 1], [2, 1], [2, 2], [2, 3], [3, 1], [3, 1], [3, 2], [3, 2]]
CREDIT: T. Yamada
Calculate the variance of an array of numbers
Examples
[].variance #=> nil [1, 2, 3].variance #=> 0.6666666666666666 [96, 35, 72, 30, 75, 33, 68, 13, 49, 71].variance #=> 609.76 [36, -67, -17, 85, -46, -64, -23, -13, 89, -47].variance #=> 2989.0099999999993 [60.7829, 31.2622, 20.626, 78.8907, 61.5328].variance #=> 459.1941339495999