Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
class Polynomial
def initialize args=[]
raise ArgumentError, "Need at least 2 coefficients." if args.size < 2
@max_exp = args.size - 1
@poly = ""
args.each_with_index do |coef, index|
# Code reading 101 : 'coef' stands for 'coefficient'.
next if coef.zero?
@coef = coef
@index = index
add_sign
add_coef
add_exp
end
@poly = "0" if @poly.empty?
end
def to_s
@poly
end
private
def add_sign
if @index > 0 # If this isn't the first argument
if @coef > 0
@poly += "+"
else
@poly += "-"
end
else # If it's the first argument, we don't care about '+'
if @coef < 0
@poly += "-"
end
end
end
def add_coef
coef = @coef.abs # We only care about the absolute value, here.
return if coef == 1
@poly += coef.to_s
end
def add_exp
exponent = @max_exp - @index # Size of the array minus where we are in the array
return if exponent.zero?
if exponent > 1
@poly += "x^#{exponent}"
else
@poly += "x"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.