Create a gist now

Instantly share code, notes, and snippets.

# Design Goal: strike a balance between terseness and readability
# I always hear Ruby developers saying Ruby code doesn't need commenting. But for
# me, no matter how well you might name those routines routines or or write
# your code, if you pair a comment clearly stating intent of the routine,
# it is always easier to quickly wrap one's head around what a block of code is
# *supposed* to be doing and you can answer the question, "does this code do what
# the author thinks its doing?" I'm still learning Ruby and I don't translate Ruby
# into a clear mental model instantly, but I generally do interpret comments quite quickly!
# Another readability enhancement is the use of parentheses to enhance readablity even when
# they're not strictly required, and the use of whitespace, such as blank line between
# guard statements that exit a routine early and the rest of the routine. Unlike other languages
# that might always require parentheses for conditionals or blocks, I've come to love
# the fact that Ruby can omit them because now when they're present, they have a semantic
# meaning to me, much like punctuation does in a sentence!
class Polynomial
# pair each given coefficient with its respective exponential as [coeff, exp], removing zeroes
def initialize(coefficients)
raise "Need at least 2 coefficients" if coefficients.size < 2
@coefficients = coefficients.reverse
@coefficients.each_with_index{ |c, i| @coefficients[i] = (c == 0 ? nil : [c, i]) }
# make 1 and -1 implicit
def multiplier_to_s(coefficient)
coefficient[0] == 1 ? "" : coefficient[0] == -1 ? "-" : coefficient[0].to_s
# only raise to power if exp is > 0
def exp_to_s(coefficient)
coefficient[1] == 0 ? "" : coefficient[1] == 1 ? "x" : "x^#{coefficient[1]}"
# return "+" only when there is no prefix and the coefficient is positive
def sign_to_s(prefix, coefficient)
(prefix == '' || coefficient[0] < 0) ? '' : "+"
# output all coefficients for the polynominal in a human readable equation.
# Example: "-3x^4-4x^3+x^2+6"
def to_s
return "0" if @coefficients.empty?
@coefficients.inject("") do |str, c|
str << sign_to_s(str, c) << multiplier_to_s(c) << exp_to_s(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment