Sha256: db2a60befcc97add336c8c4dad7116ce8510b28f6cd0b0b3762272ca36859793
Contents?: true
Size: 1.33 KB
Versions: 6
Compression:
Stored size: 1.33 KB
Contents
module Polynomials class Term attr_accessor :coefficient, :exponent def initialize(exponent = 0, coefficient = 0) @coefficient, @exponent = coefficient, exponent end def self.parse(string) term = self.new float = /\d+(?:\.\d+)?/ integer = /\d+/ polynomial_regex = / \A\s* (?<algebraic_sign>[-+]?) \s* (?<coefficient>#{float})? \s* (?<power>x(?:\^(?<exponent>#{integer}))?)? \s*\Z /x raw_data = string.match(polynomial_regex) raise NotParsableError unless raw_data term.coefficient = (raw_data[:algebraic_sign] + ( raw_data[:coefficient] || "1")).to_f term.exponent = raw_data[:power] ? (raw_data[:exponent] || 1).to_i : 0 term end def to_s pretty_coeffiecent = coefficient.denominator == 1 ? coefficient.abs.to_i : coefficient.abs algebraic_sign = coefficient < 0 ? '-' : '+' power = "x#{"^#{exponent}" unless exponent == 1}" "#{algebraic_sign} #{pretty_coeffiecent}#{ power unless exponent.zero?} " end def dup duplicate = self.class.new duplicate.coefficient = self.coefficient duplicate.exponent = self.exponent duplicate end def ==(other) self.coefficient == other.coefficient && self.exponent == other.exponent end end end
Version data entries
6 entries across 6 versions & 1 rubygems