secret
Created — forked from /michaellang.rb

  • Download Gist
michaellang.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 59
#
# 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 ArgumentError.new "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]) }
@coefficients.reverse!.compact!
end
##
# make 1 and -1 implicit
def multiplier_to_s(coefficient)
coefficient[0] == 1 ? "" : coefficient[0] == -1 ? "-" : coefficient[0].to_s
end
##
# only raise to power if exp is > 0
def exp_to_s(coefficient)
coefficient[1] == 0 ? "" : coefficient[1] == 1 ? "x" : "x^#{coefficient[1]}"
end
##
# return "+" only when there is no prefix and the coefficient is positive
def sign_to_s(prefix, coefficient)
(prefix == '' || coefficient[0] < 0) ? '' : "+"
end
##
# 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)
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.