I've written a small function for solving simple quadratic equations:
class EquationSolver
def solve(x, *args)
args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element }
end
end
To calculate f(3)
for f(x)=3x3−2x2−x+5
, one would write:
puts EquationSolver.new.solve(3, 3, -2, -1, 5)
However, is there a more elegant version of my function, more like reduce.with_index
or something similar?