Module: ParaDice::Utility

Defined in:
lib/para_dice/utility.rb

Overview

provides utility methods used by other parts of ParaDice.

Class Method Summary collapse

Class Method Details

.from_summary(summary) ⇒ Array<Object>

from_summary creates an array and populates with a number of each key

equal to the value for that key

Examples:

Make an array from a Summary Hash

summary = {foo: 3, bar: 1, baz: 2}
ParaDice::Utility.from_summary(summary) # => [:foo,:foo,:foo,:bar,:baz,:baz]

Parameters:

  • summary (Hash<Object,Fixnum>)

    a hash to inflate a summary into an array

Returns:

  • (Array<Object>)


48
49
50
# File 'lib/para_dice/utility.rb', line 48

def self.from_summary(summary)
  summary.each_pair.map { |e, c| Array.new(c) { e } }.flatten
end

.module_from(name, namespace = nil) ⇒ false, ...

Generate a Class or Module from a representation for the class.

Examples:

Get a module from

ParaDice::Utility.module_from(String) # => String
ParaDice::Utility.module_from('string') # => String
ParaDice::Utility.module_from('String') # => String
ParaDice::Utility.module_from('STRING') # => String
ParaDice::Utility.module_from(:string) # => String
ParaDice::Utility.module_from(:String) # => String
ParaDice::Utility.module_from('paradise/utility') # => Paradise::Utility
ParaDice::Utility.module_from('paradise__utility') # => Paradise::Utility
ParaDice::Utility.module_from('Paradise::Utility') # => Paradise::Utility
ParaDice::Utility.module_from('Utility', 'ParaDice') # => Paradise::Utility
ParaDice::Utility.module_from('Utility', ParaDice) # => Paradise::Utility

Parameters:

  • name (Class, Module, #to_s)
  • namespace (Class, Module, #to_s) (defaults to: nil)

Returns:

  • (false)

    if no name is found at top level or namespace

  • (Class, Module)

    the class or module represented by name and optionally in namespace



24
25
26
27
28
# File 'lib/para_dice/utility.rb', line 24

def self.module_from(name, namespace = nil)
  return name if name.is_a? Module
  return false if name.empty?
  self.module_from_top(name) || self.module_from_namespace(name, namespace)
end

.to_summary(arr) ⇒ Hash

to_summary creates a hash and populates it with uniq elements of the

array, and the count of how many there are

Examples:

Make a summary from array

arr = [2,3,1,2,3,2,3]
ParaDice::Utility.to_summary(arr) # => { 1 => 1, 2 => 3, 3 => 3}

Parameters:

  • arr (Array)

    a list to summarize

Returns:

  • (Hash)


37
38
39
# File 'lib/para_dice/utility.rb', line 37

def self.to_summary(arr)
  arr.reduce(Hash.new(0)) { |h, e| h[e] += 1; h }
end