Module Enumerable
In: lib/facets/core/enumerable/probability.rb
lib/facets/core/enumerable/elementwise.rb
lib/facets/core/enumerable/one.rb
lib/facets/core/enumerable/cart.rb
lib/facets/core/enumerable/each_with_counter.rb
lib/facets/core/enumerable/accumulate.rb
lib/facets/core/enumerable/cascade.rb
lib/facets/core/enumerable/to_h.rb
lib/facets/core/enumerable/every.rb
lib/facets/core/enumerable/ideal_entropy.rb
lib/facets/core/enumerable/each_by.rb
lib/facets/core/enumerable/collect_with_index.rb
lib/facets/core/enumerable/compact_collect.rb
lib/facets/core/enumerable/graph.rb
lib/facets/core/enumerable/partition_by.rb
lib/facets/core/enumerable/divide.rb
lib/facets/core/enumerable/each_pair.rb
lib/facets/core/enumerable/occur.rb
lib/facets/core/enumerable/find_collisions.rb
lib/facets/core/enumerable/nonuniq.rb
lib/facets/core/enumerable/mode.rb
lib/facets/core/enumerable/eachn.rb
lib/facets/core/enumerable/sum.rb
lib/facets/core/enumerable/count.rb
lib/facets/core/enumerable/filter_collect.rb
lib/facets/core/enumerable/commonality.rb
lib/facets/core/enumerable/none.rb
lib/facets/core/enumerable/entropy.rb
lib/facets/core/enumerable/frequency.rb
lib/facets/core/enumerable/collect_if.rb
lib/facets/core/enumerable/op_pow.rb
lib/facets/core/enumerable/project.rb
lib/facets/core/enumerable/uniq_by.rb
lib/facets/core/enumerable/where.rb
lib/facets/core/enumerable/permutation.rb
lib/facets/core/enumerable/injecting.rb
lib/facets/core/enumerable/thread_map.rb
lib/facets/core/enumerable/map_send.rb
lib/facets/core/enumerable/op_tilde_self.rb
lib/facets/core/enumerable/self/combinations.rb
lib/facets/yore/enumerable/cross.rb

injecting.rb

CREDIT Louis J Scoras

Methods

External Aliases

cartesian_product -> cart
each_with_index -> each_with_counter
  More appropriate naming since an enumerable is not neccesarily "indexed", as is an Array or Hash.

Public Class methods

Provides the cross-product of two or more Enumerables. This is the class-level method. The instance method calls on this.

  Enumerable.cross([1,2], [4], ["apple", "banana"])
  #=> [[1, 4, "apple"], [1, 4, "banana"], [2, 4, "apple"], [2, 4, "banana"]]

  Enumerable.cross([1,2], [3,4])
  #=> [[1, 3], [1, 4], [2, 3], [2, 4]]

Produces an array of arrays of all possible combinations of the given arrays in the positions given. (Imagine it like a slot machine dial. This gives evey combination that could come up.)

  a = %w|a b|
  b = %w|a x|
  c = %w|x y|
  Array.combinations(a, b, c).each { |x| p x }

produces

  ["a", "a", "x"]
  ["a", "a", "y"]
  ["a", "x", "x"]
  ["a", "x", "y"]
  ["b", "a", "x"]
  ["b", "a", "y"]
  ["b", "x", "x"]
  ["b", "x", "y"]

Provides the cross-product of two or more Enumerables. This is the class-level method. The instance method calls on this.

  Enumerable.cross([1,2], [4], ["apple", "banana"])
  #=> [[1, 4, "apple"], [1, 4, "banana"], [2, 4, "apple"], [2, 4, "banana"]]

  Enumerable.cross([1,2], [3,4])
  #=> [[1, 3], [1, 4], [2, 3], [2, 4]]

Public Instance methods

Operator alias for cross-product.

  a = [1,2] ** [4,5]
  a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]

Project has_many Group Group has_many User projects.groups.accumulate.users

cart(*enums, &block)

Alias for cartesian_product

The instance level version of Enumerable::cartesian_product.

  a = []
  [1,2].cart([4,5]){|elem| a << elem }
  a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]

Cascade actions on each enumerated element.

[9, 19, 29].cascade :succ, :to_s, :reverse

> ["01", "02", "03"]

collect_with_counter()

Alias for collect_with_index

Same as collect but with an iteration counter.

  a = [1,2,3].collect_with_index { |e,i| e*i }
  a  #=> [0,2,6]

Returns all items that are equal in terms of the supplied block. If no block is given objects are considered to be equal if they return the same value for Object#hash and if obj1 == obj2. No guarantee about the order of the elements in the resulting array is made.

Note: The result will be an array if you supply no block and a hash otherwise.

  [1, 2, 2, 3, 4, 4].commonality # => { 2 => [2], 4 => [4] }

  ["foo", "bar", "a"].commonality { |str| str.length }
  # => { 2 => ["foo, "bar"] }

  # Returns all persons that share their last name with another person.
  persons.collisions { |person| person.last_name }

Collects/Maps and compacts items in one single step. The items for which the supplied block returns nil will not end up in the resulting array.

  # Return telephone numbers of all persons that have a telephone number.
  persons.compact_collect { |person| person.telephone_no }

Also see Enumerable#collect, Enumerable#map, Array#compact.

compact_map(

Alias for compact_collect

Count the number of items in an enuerable equal (==) to the given object.

  e = [ 'a', '1', 'a' ]
  e.count('1')    #=> 1
  e.count('a')    #=> 2

Count can also handle multiple-valued blocks.

  e = { 'a' => 2, 'a' => 2, 'b' => 1 }
  e.count('a',2)  #=> 1

The instance level version of Enumerable::cartesian_product.

  a = []
  [1,2].cart([4,5]){|elem| a << elem }
  a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]

Split an array on matching pattern.

[‘a1’,’b1’,’a2’,’b2’].divide(/^a/)

> [[‘a1,’b1’],[‘a2’,’b2’]]

Iterate through slices. If slicing step is not given, the the arity if the block is used.

  x = []
  [1,2,3,4].each_by{ |a,b| x << [a,b] }
  x  #=> [ [1,2], [3,4] ]

  x = []
  [1,2,3,4,5,6].each_by(3){ |a| x << a }
  x  #=> [ [1,2,3], [4,5,6] ]

Iterators ovr each element pairing.

  [:a,:b,:c,:d].each_pair { |a,b|  puts "#{a} -> #{b}" }

produces

  a -> b
  c -> d

Applys a block to each possible permutation of an array/enumerable.

  %w[a b c].each_permutation { |x| puts(x.join('')) }

produces

  abc
  acb
  bac
  bca
  cab
  cba

Returns an elementwise Functor designed to make R-like elementwise operations possible.

  [1,2].elements + 3          #=> [4,5]
  [1,2].elements + [4,5]      #=> [5,7]
  [1,2].elements + [[4,5],3]  #=> [[5,7],[4,5]

Shannon‘s entropy for an array - returns the average bits per symbol required to encode the array. Lower values mean less "entropy" - i.e. less unique information in the array.

  %w{ a b c d e e e }.entropy  #=>

Returns an elementwise Functor. This allows you to map a method on to every element.

  [1,2,3].every + 3           #=> [4,5,6]

  ['a','b','c'].every.upcase  #=> ['A','B','C']
ew()

Alias for elementwise

Collects/Maps and filters items out in one single step. You can use throw(:skip) in the supplied block to indicate that the current item should not end up in the resulting array.

  # Return names of all person with an age of at least 18.
  persons.filter_collect do |person|
    throw(:skip) if person.age < 18
    person.name
  end

Also see Enumerable#collect, Enumerable#find_all.

filter_map(

Alias for filter_collect

Like commonality but returns an array if no block is given.

Generates a hash mapping each unique symbol in the array to the absolute frequency it appears.

Like map/collect, but it generates a Hash. The block is expected to return two values: the key and the value for the new hash.

  numbers  = (1..3)
  squares  = numbers.graph { |n| [n, n*n] }   # { 1=>1, 2=>4, 3=>9 }
  sq_roots = numbers.graph { |n| [n*n, n] }   # { 1=>1, 4=>2, 9=>3 }

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).

Say you want to count letters—

   some_text.injecting(Hash.new(0) {|h,l| h[l] += 1}

vs

   some_text.inject(Hash.new(0)) {|h,l| h[l] +=1; h}
map_if(&b)

Alias for collect_if

map_with_counter()

Alias for collect_with_index

map_with_index()

Alias for collect_with_index

In Statistics mode is the value that occurs most frequently in a given set of data.

Enumerable#none? is the logical opposite of the builtin method Enumerable#any?. It returns true if and only if none of the elements in the collection satisfy the predicate.

If no predicate is provided, Enumerable#none? returns true if and only if none of the elements have a true value (i.e. not nil or false).

  [].none?                      # true
  [nil].none?                   # true
  [5,8,9].none?                 # false
  (1...10).none? { |n| n < 0 }  # true
  (1...10).none? { |n| n > 0 }  # false

Returns an array of elements for the elements that occur n times. Or according to the results of a given block.

  [1,1,2,3,3,4,5,5].occur(1)             #=> [2,4]
  [1,1,2,3,3,4,5,5].occur(2)             #=> [1,3,5]
  [1,1,2,3,3,4,5,5].occur(3)             #=> []

  [1,2,2,3,3,3].occur(1..1)              #=> [1]
  [1,2,2,3,3,3].occur(2..3)              #=> [2,3]

  [1,1,2,3,3,4,5,5].occur { |n| n == 1 } #=> [2,4]
  [1,1,2,3,3,4,5,5].occur { |n| n > 1 }  #=> [1,3,5]

Enumerable#one? returns true if and only if exactly one element in the collection satisfies the given predicate.

If no predicate is provided, Enumerable#one? returns true if and only if exactly one element has a true value (i.e. not nil or false).

  [].one?                      # false
  [nil].one?                   # false
  [5].one?                     # true
  [5,8,9].one?                 # false
  (1...10).one? { |n| n == 5 } # true
  (1...10).one? { |n| n < 5 }  # false

See Enumerable#partition for the background. partition_by is best explained by example.

  (1..5).partition_by { |n| n % 3 }
       #=> { 0 => [3], 1 => [1, 4], 2 => [2,5] }

  ["I had", 1, "dollar and", 50, "cents"].partition_by { |e| e.class }
       #=> { String => ["I had","dollar and","cents"], Fixnum => [1,50] }

partition_by is used to group items in a collection by something they have in common. The common factor is the key in the resulting hash, the array of like elements is the value.

Permutation proves the possible orders of an enumerable. Each is index by a oermutation numnber. The maximum number of arrangements is the factorial of the size of the array.

permute(number)

Alias for permutation

Generates a hash mapping each unique symbol in the array to the relative frequency, i.e. the probablity, of it appearence.

Uses #+ to sum the enumerated elements.

  [1,2,3].sum  #=> 6
  [3,3,3].sum  #=> 9

Produces a hash from an Enumerable with index for keys.

  enu = 'a'..'b'
  enu.to_h  #=> { 0=>'a', 1=>'b' }

If a block is passed, the hash values will be set by calling the block with the enumerated element and it‘s counter.

  enu = 'a'..'b'
  enu.to_h{ |e,i| e }  #=> { 0=>'a', 1=>'b' }

See also graph.

Like uniq, but determines uniqueness based on a given block.

  (-5..5).to_a.uniq_by {|i| i*i }

produces

  [-5, -4, -3, -2, -1, 0]

Operator equivalent of elementwise.

[Validate]