secret
Last active — forked from pharrington/paulharrington.rb

  • Download Gist
paulharrington.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
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.