Module: Molecules::Utils
- Included in:
- EmpiricalFormula
- Defined in:
- lib/molecules/utils.rb
Overview
A number of utility routines used by EmpiricalFormula and elsewhere. These methods are used a great deal and are all prime candidates for optimization (for example using RubyInline).
Class Method Summary collapse
-
.add(a, b, n = 1) ⇒ Object
Adds the elements of b to a at corresponding indicies, multiplying by n.
-
.count(str, patterns) ⇒ Object
Collects the number of each of the patterns in str.
-
.multiply(a, factor) ⇒ Object
Multiples the elements of array a by factor, returning a.
-
.round(n, precision) ⇒ Object
Rounds n to the specified precision (ie number of decimal places).
Class Method Details
.add(a, b, n = 1) ⇒ Object
Adds the elements of b to a at corresponding indicies, multiplying by n. The input arrays do not have to be the same length. Returns a with trailing zeros removed.
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/molecules/utils.rb', line 19 def add(a, b, n=1) a << 0 while a.length < b.length # oddly, this is faster than each_with_index i = 0 b.each do |factor| a[i] += n * factor i += 1 end a.pop while a[-1] == 0 a end |
.count(str, patterns) ⇒ Object
Collects the number of each of the patterns in str. For example:
count("abcabca", ["a", "b", "c"]) # => [3, 2, 2]
count("abcabca", ["a", "bc"]) # => [3, 4]
44 45 46 |
# File 'lib/molecules/utils.rb', line 44 def count(str, patterns) patterns.collect {|pattern| str.count(pattern)} end |
.multiply(a, factor) ⇒ Object
Multiples the elements of array a by factor, returning a. Clears a if factor == 0.
35 36 37 |
# File 'lib/molecules/utils.rb', line 35 def multiply(a, factor) factor == 0 ? a.clear : a.collect! {|i| i * factor} end |
.round(n, precision) ⇒ Object
Rounds n to the specified precision (ie number of decimal places)
10 11 12 13 |
# File 'lib/molecules/utils.rb', line 10 def round(n, precision) factor = 10**precision.to_i (n * factor).round.to_f / factor end |