secret
Last active

  • Download Gist
benoitdaloze.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 27
# Benoit Daloze
# Ruby Programming Challenge For Newbies #4
# pretty-print polynomials
#
# My solution use Enumerable#inject to build the String,
# with every "monomial" splitted in 3 parts : sign, coefficient and variable
class Polynomial
def initialize(coef)
raise ArgumentError, "Need at least 2 coefficients" if coef.size < 2
@coef = coef
end
def to_s
return '0' if @coef.all? { |c| c == 0 }
(0...@coef.length).inject("") { |s, i|
coef, pow = @coef[i], @coef.length-1-i
if coef == 0
s
else
s +
(coef > 0 ? '+' : '-') + # sign
(coef.abs == 1 && pow != 0 ? '' : coef.abs.to_s) + # coef
(pow < 2 ? 'x'*pow : "x^#{pow}") # var
end
}.sub(/^\+/, "")
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.