public
Last active — forked from enkrates/polynomial.rb

  • Download Gist
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
class Polynomial
def initialize array
if array.length <= 1
raise ArgumentError.new('Need at least 2 coefficients')
exit
else
@return_string = ''
@iterations = array.length - 1
array.each do |item|
if @iterations > 1
@this_iteration = "^#{@iterations}"
else
@this_iteration = ''
end
if item.abs > 0
if item > 1
if @return_string.empty?
@item_string = "#{item}"
else
@item_string = "+#{item}"
end
elsif item < -1
@item_string = "#{item}"
elsif (item == 1)
if @return_string.empty?
@item_string = ''
else
@item_string = '+'
end
elsif item == -1
@item_string = '-'
end
if @iterations > 0
@item_string = "#{@item_string}x"
end
@return_string << "#{@item_string}#{@this_iteration}"
end
@iterations = @iterations - 1
end
if @return_string.empty?
@return_string = '0'
end
end
end
def to_s
@return_string
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.