Skip to content

@pharrington /paulharrington.rb secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Ruby newbie challenge #4; i apparently have a phobia of unnecessary string allocation
class Polynomial
def initialize ary
raise ArgumentError, "Need at least 2 coefficients" unless ary.size > 1
@coeffs = ary.reverse # low order terms first
@coeffs.pop while @coeffs.last == 0
end
def to_s
return "0" if @coeffs.all? {|c| c == 0} # short circuit if all terms are 0
str = ""
@coeffs.each_with_index do |coeff, exp|
unless coeff == 0 # skip terms that are 0
op = if coeff == @coeffs.last && coeff > 0 # don't display the sign of the last term if positive
:""
else
coeff > 0 ? :+ : :-
end
coeff_str = coeff.abs == 1 ? :"" : coeff.abs.to_s # don't display the coefficient if it's 1
exp_str = exp > 1 ? "^#{exp}" : :"" # don't display the exponent if it's 1
var = exp > 0 ? :x : :"" # the first term is a constant; do not display a variable
str.insert 0, "" << op << coeff_str << var << exp_str
end
end
str
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.