public

  • Download Gist
RPCFN4_-_Pretty_Polynomial.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
class Polynomial
 
def initialize(coeffs)
raise ArgumentError.new("Need at least 2 coefficients.") if coeffs.size < 2
@coeffs = coeffs
end
 
def to_s
output = []
coeffs = @coeffs.dup
coeffs.size.times do |index|
coeff = coeffs.pop
if coeff != 0
output << "^#{index}" if index > 1
output << 'x' if index > 0
output << coeff
output << '+' if coeff > 0 and
coeffs.select { |c| c != 0 }.size > 0
end
end
output.reverse.join
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.