Instantly share code, notes, and snippets.

# RLGGHC/polynomial.rbSecret forked from milandobrota/polynomial.rb Created Nov 28, 2009

What would you like to do?
 class ArgumentError < StandardError; end class Polynomial def initialize(coefficients) raise ArgumentError.new("Need at least 2 coefficients") if coefficients.size < 2 @addends = [] size = coefficients.size coefficients.each_with_index do |coef, index| unless coef == 0 if index == size-1 @addends << "#{coef}" elsif index == size -2 @addends << "#{coef}x" elsif coef == 1 @addends << "x^#{size-index-1}" elsif coef == -1 @addends << "-x^#{size-index-1}" else @addends << "#{coef}x^#{size-index-1}" end end end end def to_s @addends.empty? ? 0.to_s : @addends.join("+").gsub("+-", "-") end end
 require 'polynomial' describe Polynomial do before do @p1 = Polynomial.new([-3,-4,1,0,6]) @p2 = Polynomial.new([1,0,2]) @p3 = Polynomial.new([-1,-2,3,0]) @p4 = Polynomial.new([0,0,0]) end it "should test first negative" do @p1.to_s.should == "-3x^4-4x^3+x^2+6" end it "should test simple" do @p2.to_s.should == "x^2+2" end it "should test first minus one" do @p3.to_s.should == "-x^3-2x^2+3x" end it "should test all zero" do @p4.to_s.should == "0" end it "should test error" do lambda{ Polynomial.new([1])}.should raise_error(ArgumentError, /Need at least 2 coefficients/) end end