Polynomial equation solver in Ruby 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?
Yes, there is a more elegant version. Here it is:

class EquationSolver
  def solve(x, *args)
    args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
  end
end


It's possible to do this because iterator methods like each_with_index, when called without a block, return an Enumerator object on which you can call all the methods of the Enumerable.

In fact, an even shorter solution is obtained by using a variation of reduce to use a symbolic operator:

class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)
  end
end