# Forum: Ruby axÂ²+bx+c for newbies

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
on 2007-04-25 19:57
```Here is some very easy code to understand.
Since I started learning Ruby 2 years ago, I lacked examples.
So if this code can help newbies, the goal will be achieved.

Ytoba

include Math
require 'complex'
require 'rational'

begin

class Eq2
def initialize(a,b,c)
@a, @b, @c = Rational(a,1), Rational(b,1), Rational(c,1)
end

def to_s
ch = ""
ch += "#{@a}" unless @a == 1
ch += "-" if @a == -1
ch += "xÂ²"
ch += "+" unless @b < 0
ch += "#{@b}" unless @b == 1
ch += "-" if @b == -1
ch += "x"
ch += "+" unless @c < 0
ch += "#{@c}" unless @c == 1
ch += "-" if @c == -1
ch
end

def delta
@b*@b - Rational(4,1)*@a*@c
end

def solve
dlt = delta
puts "delta=#{dlt}"
case
when dlt > 0
r1 = (-@b - sqrt(delta))/(2*@a).to_f
r2 = (-@b + sqrt(delta))/(2*@a).to_f
puts "Two distinct roots"
puts "r1=#{r1}"
puts "r2=#{r2}"
when dlt == 0
puts "A double root"
r= -@b/(2*@a)
puts "r=#{r}"
when dlt < 0
puts "delta=#{-delta}iÂ²"
puts "Two complex roots"
r1 = Complex(-@b/(2*@a).to_f, -sqrt(-delta)/(2*@a).to_f)
r2 = Complex(-@b/(2*@a).to_f, sqrt(-delta)/(2*@a).to_f)
puts "r1=#{r1}"
puts "r2=#{r2}"
end

end
end

e = Eq2.new(1,-6,4)

puts e
e.solve

f = Eq2.new(1,2,5)
puts f
f.solve

end```
This topic is locked and can not be replied to.