module Mspire::MolecularFormula::Arithmetic

Public Instance Methods

*(int) click to toggle source
# File lib/mspire/molecular_formula/arithmetic.rb, line 40
def *(int)
  self.dup.mul!(int)
end
+(*others) click to toggle source

returns a new formula object where all the atoms have been added up

# File lib/mspire/molecular_formula/arithmetic.rb, line 5
def +(*others)
  self.dup.add!(*others)
end
-(*others) click to toggle source

returns a new formula object where all the formulas have been subtracted from the caller

# File lib/mspire/molecular_formula/arithmetic.rb, line 20
def -(*others)
  self.dup.sub!(*others)
end
/(int) click to toggle source
# File lib/mspire/molecular_formula/arithmetic.rb, line 53
def /(int)
  self.dup.div!(int)
end
add!(*others) click to toggle source

returns self

# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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