Sha256: 9abe7cd0072c041f2b1c12c9bdcbb5eb45c490c6438a89bec808f405fb4067b9

Contents?: true

Size: 992 Bytes

Versions: 2

Compression:

Stored size: 992 Bytes

Contents

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*/
    raw_data = string.match(/(?<algebraic_sign>[-+]?)\s*(?<coefficient>#{float})?\s*(?<power>x.*)?\s*\Z/)
    term.coefficient = (raw_data[:algebraic_sign] + (!raw_data[:coefficient].empty? ? raw_data[:coefficient] : "1")).to_f
    term.exponent = (raw_data[:power] ? (raw_data[:power] =~ /x\^(#{integer})/ ?  $1.to_i : 1) : 0)
    term
  end

  def to_s
    "#{ (coefficient < 0) ? '-' : '+' } #{coefficient.abs} #{ "x#{"^#{exponent}" unless exponent == 1}" 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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polynomials-0.1.7 lib/term.rb
polynomials-0.1.6 lib/term.rb