Class: Polynomials::Term

Inherits:
Object
  • Object
show all
Defined in:
lib/polynomials/term.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exponent = 0, coefficient = 0) ⇒ Term

Returns a new instance of Term.



5
6
7
# File 'lib/polynomials/term.rb', line 5

def initialize(exponent = 0, coefficient = 0)
  @coefficient, @exponent = coefficient, exponent
end

Instance Attribute Details

#coefficientObject

Returns the value of attribute coefficient.



3
4
5
# File 'lib/polynomials/term.rb', line 3

def coefficient
  @coefficient
end

#exponentObject

Returns the value of attribute exponent.



3
4
5
# File 'lib/polynomials/term.rb', line 3

def exponent
  @exponent
end

Class Method Details

.parse(string) ⇒ Object

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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

Instance Method Details

#==(other) ⇒ Object



44
45
46
# File 'lib/polynomials/term.rb', line 44

def ==(other)
  self.coefficient == other.coefficient && self.exponent == other.exponent
end

#dupObject



37
38
39
40
41
42
# File 'lib/polynomials/term.rb', line 37

def dup
  duplicate = self.class.new
  duplicate.coefficient = self.coefficient
  duplicate.exponent = self.exponent
  duplicate
end

#to_sObject



30
31
32
33
34
35
# 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