Module: Mspire::MolecularFormula::Arithmetic
- Included in:
- Mspire::MolecularFormula
- Defined in:
- lib/mspire/molecular_formula/arithmetic.rb
Instance Method Summary collapse
- #*(int) ⇒ Object
-
#+(*others) ⇒ Object
returns a new formula object where all the atoms have been added up.
-
#-(*others) ⇒ Object
returns a new formula object where all the formulas have been subtracted from the caller.
- #/(int) ⇒ Object
-
#add!(*others) ⇒ Object
returns self.
- #div!(int, also_do_charge = true) ⇒ Object
- #mul!(int, also_do_charge = true) ⇒ Object
- #sub!(*others) ⇒ Object
Instance Method Details
#*(int) ⇒ Object
40 41 42 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 40 def *(int) self.dup.mul!(int) end |
#+(*others) ⇒ Object
returns a new formula object where all the atoms have been added up
5 6 7 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 5 def +(*others) self.dup.add!(*others) end |
#-(*others) ⇒ Object
returns a new formula object where all the formulas have been subtracted from the caller
20 21 22 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 20 def -(*others) self.dup.sub!(*others) end |
#/(int) ⇒ Object
53 54 55 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 53 def /(int) self.dup.div!(int) end |
#add!(*others) ⇒ Object
returns self
10 11 12 13 14 15 16 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 10 def add!(*others) others.each do |other| self.merge!(other) {|key, oldval, newval| self[key] = oldval + newval } self.charge += other.charge end self end |
#div!(int, also_do_charge = true) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 57 def div!(int, also_do_charge=true) raise ArgumentError, "must be an integer" unless int.is_a?(Integer) self.each do |k,v| quotient, modulus = v.divmod(int) raise ArgumentError "all numbers must be divisible by int" unless modulus == 0 self[k] = quotient end if also_do_charge quotient, modulus = self.charge.divmod(int) raise ArgumentError "charge must be divisible by int" unless modulus == 0 self.charge = quotient end self end |
#mul!(int, also_do_charge = true) ⇒ Object
44 45 46 47 48 49 50 51 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 44 def mul!(int, also_do_charge=true) raise ArgumentError, "must be an integer" unless int.is_a?(Integer) self.each do |k,v| self[k] = v * int end self.charge *= int if also_do_charge self end |
#sub!(*others) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/mspire/molecular_formula/arithmetic.rb', line 24 def sub!(*others) others.each do |other| oth = other.dup self.each do |k,v| if oth.key?(k) self[k] -= oth.delete(k) end end oth.each do |k,v| self[k] = -v end self.charge -= other.charge end self end |