Sha256: 32062377f3d4dadba92d6a759158405ce5ed8ab9142cc92bff56582f086202ca

Contents?: true

Size: 876 Bytes

Versions: 5

Compression:

Stored size: 876 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(/([-+]?)\s*#{float}\s*(x.*)?\s*\Z/)
    term.coefficient = (raw_data[1] + raw_data[2]).to_f
    term.exponent = (raw_data[3] ? (raw_data[3] =~ /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

5 entries across 5 versions & 1 rubygems

Version Path
polynomials-0.1.5 lib/term.rb
polynomials-0.1.4 lib/term.rb
polynomials-0.1.2 lib/term.rb
polynomials-0.1.1 lib/term.rb
polynomials-0.1.0 lib/term.rb