1
\$\begingroup\$

I wrote a simple quadratic equation solver with Ruby to help me solve quadratic equations. Please tell me what I did right or wrong, and what I can do to improve it.

#!/usr/bin/ruby

if ARGV.length != 3
        STDERR << "Usage: #{$0} <a> <b> <c>\n"
        exit 1
end

a = ARGV[0].to_i
b = ARGV[1].to_i
c = ARGV[2].to_i

disc = b**2 - 4*a*c
d_str = (disc >= 0) ? (Math.sqrt(disc) % 1 == 0) ? Math.sqrt(disc).to_i : "√#{disc}" : "√#{disc}"

s = "#{-b} ± #{d_str}"
d = "#{2*a}"
puts "\e[4m#{s}\e[0m"
#puts "─"*(s.length)
puts d.center s.length
\$\endgroup\$
  • \$\begingroup\$ I would show the calculated value Math.sqrt(disc) even when it is a floating point number. Its also a good idea to check before using terminal control codes (A simple, though not foolproof, way is to check $stdout.isatty). The colorize gem is also, though ti does add a dependency to your code. \$\endgroup\$ – Marc Rohloff Mar 2 '17 at 17:29
  • \$\begingroup\$ Any updates on this? \$\endgroup\$ – Dmitry Kudriavtsev Mar 4 '17 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.