# axÂ²+bx+c for newbies

**URL:** <https://www.ruby-forum.com/t/axa-bx-c-for-newbies/92918>\
**Category:** Ruby\
**Created:** [April 25, 2007, 5:57pm UTC](https://www.ruby-forum.com/t/axa-bx-c-for-newbies/92918 "2007-04-25T17:57:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ytoba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/b782af/32.png) [@Ytoba](https://www.ruby-forum.com/u/Ytoba)\
**Post date:** [April 25, 2007, 5:57pm UTC](https://www.ruby-forum.com/t/axa-bx-c-for-newbies/92918/1 "2007-04-25T17:57:12Z")

</div>

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
