class Polynomials::Term
Attributes
coefficient[RW]
exponent[RW]
Public Class Methods
new(exponent = 0, coefficient = 0)
click to toggle source
# File lib/polynomials/term.rb, line 5 def initialize(exponent = 0, coefficient = 0) @coefficient, @exponent = coefficient, exponent end
parse(string)
click to toggle source
# File lib/polynomials/term.rb, line 9 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
Public Instance Methods
==(other)
click to toggle source
# File lib/polynomials/term.rb, line 44 def ==(other) self.coefficient == other.coefficient && self.exponent == other.exponent end
dup()
click to toggle source
# File lib/polynomials/term.rb, line 37 def dup duplicate = self.class.new duplicate.coefficient = self.coefficient duplicate.exponent = self.exponent duplicate end
to_s()
click to toggle source
# File lib/polynomials/term.rb, line 30 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