public
Last active — forked from chrisjones/polynomial.rb

  • Download Gist
polynomial.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#!/usr/bin/ruby
 
class Polynomial
 
def initialize(coefficients)
if coefficients.length < 2
raise ArgumentError, 'Need at least 2 coefficients.'
end
order = coefficients.length - 1
@poly = ""
coefficients.each do |c|
unless c == 0
if order != coefficients.length - 1 and c > 0
@poly << "+"
end
@poly << c.to_s unless c.abs == 1
@poly << "-" if c == -1
@poly << "x" unless order < 1
@poly << "^" + order.to_s unless order < 2
end
order -= 1
end
end
 
def to_s
@poly.empty? ? "0" : @poly
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.