Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Adam Lum's solution to RPCFN #4 (Ruby**Fun)
# Adam Lum's solution to RPCFN #4
# http://rubylearning.com/blog/2009/11/26/rpcfn-rubyfun-4/
class Polynomial
attr_accessor :coefficient_array
def initialize(in_coefficient_array)
if (in_coefficient_array.size < 2)
raise ArgumentError, "Need at least 2 coefficients."
end
@coefficient_array = in_coefficient_array
end
def to_str
to_s
end
def to_s
return_string = ""
coefficient_count = @coefficient_array.size - 1
@coefficient_array.each do |c|
if (c != 0)
if (c > 1)
return_string += "+#{c.to_s}"
elsif (c == 1)
if (coefficient_count != @coefficient_array.size - 1)
return_string += "+"
end
elsif (c == -1)
return_string += "-"
else
return_string += c.to_s
end
if (coefficient_count > 1)
return_string += "x^#{coefficient_count}"
elsif (coefficient_count == 1)
return_string += "x"
end
end
coefficient_count -= 1
end
if (return_string.length <= 0)
return_string = "0"
end
return_string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment