Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class Polynomial
attr_reader :coeffs
def initialize(coeffs)
raise ArgumentError, "Need at least 2 coefficients", caller if coeffs.length <= 2
@coeffs = coeffs
def to_s
polynom = "" #initialize empty string to create polynomial expression
@coeffs.each_with_index do |coeff,index|
exponent = @coeffs.length - index - 1 #countdown exponent value starting from 1 less than number of coefficients passed
if coeff != 0 #Don't do anything if 0 value is passed for current coefficient
polynom += "+" if (coeff >= 0 and polynom != "")
#Add a plus sign if coefficient is positive unless on first item of array or there has been no output so far
polynom += coeff.to_s unless (coeff == 1 and exponent != 0)
#Add the coefficient to polynomial unless is a 1 value or on the final coefficient
polynom.chop! if coeff == -1
#Remove the 1 if the coefficient is -1 (leaving just a minus sign)
polynom += "x" unless exponent == 0
#Add x for all but last coefficient
polynom += "^" + exponent.to_s if exponent > 1
#Add ^exponent for all but last 2 coefficients
polynom == "" ? "0" : polynom #set polynom to "0" if nothing has been output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.