Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from chrisjones/polynomial.rb
Created November 30, 2009 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/245165 to your computer and use it in GitHub Desktop.
Save RLGGHC/245165 to your computer and use it in GitHub Desktop.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment