class Eulim::Chemistry::Compound

This class has functionality for compounds Ex: constituent elements, molecular mass, etc

Constants

COMPOUND_REGEXP

Attributes

constituents[RW]
formula[RW]
molar_mass[RW]
molecular_mass[RW]

Public Class Methods

new(arg) click to toggle source
# File lib/eulim/chemistry/compound.rb, line 13
def initialize(arg)
  @formula = arg
  build_constituents
  calculate_mass
end

Private Instance Methods

build_constituents() click to toggle source
# File lib/eulim/chemistry/compound.rb, line 29
def build_constituents
  @constituents = {}
  get_const_atoms.each do |symbol, count|
    @constituents[symbol] = {
      element: Element.get_by_symbol(symbol),
      atom_count: count
    }
  end
  @constituents
end
calculate_mass() click to toggle source
# File lib/eulim/chemistry/compound.rb, line 21
def calculate_mass
  @molecular_mass = Unitwise(0.0, 'u')
  @constituents.each do |_symbol, info|
    @molecular_mass += info[:element].atomic_mass * info[:atom_count]
  end
  @molar_mass = Unitwise(@molecular_mass.value / 1000.0, 'kg/mol')
end
get_const_atoms(formula = @formula, r = {}) click to toggle source
# File lib/eulim/chemistry/compound.rb, line 40
def get_const_atoms(formula = @formula, r = {})
  formula.scan(COMPOUND_REGEXP).each do |const|
    multipler = get_multipler const
    if const[0] != '(' && multipler.zero?
      r[const] = r[const] ? r[const] + 1 : 1
    else
      (multipler.zero? ? 1 : multipler).times do
        sub_const = const.match(/^\(?(.*?)\)?($|\d*$)/).to_a
        get_const_atoms sub_const[const == sub_const.first ? 1 : 0], r
      end
    end
  end
  r
end
get_multipler(const) click to toggle source
# File lib/eulim/chemistry/compound.rb, line 55
def get_multipler(const)
  multipler = const.match(/\d*$/).to_a.first.to_i
  multipler
end