Rational Number

Guide me to use the Rational number in Ruby.

what is the way? to use the rational number as,
a=3/4
puts a #=> 3/4
arr=[2/3,3/4,5/8,9/5] #=> [2/3,3/4,5/8,9/5]
hsh={sub1: 1/6, sub3: 3/6, sub4: 5/6}
#=>{‘sub1’=>1/6, ‘sub3’=>3/6, ‘sub4’=>5/6}

3/4 #=> 0 Integer Math as it should be
Rational(3,4) #=> (3/4)
require “mathn” #=> true
3/4 #=> (3/4)

Using mathn in a program is normally not a good idea because it changes
integer division globally and other operators.

Without mathn you can use for example:

Rational(3, 4)
"3/4".to_r
0.75r # Ruby 2.1 only

It is important to note that in Ruby 2.1 the literal 0.75r is exact.

Let me explain: Expressions like 0.1.to_r should be totally avoided
(unless
for some reason that’s what you actually mean), because that is a method
(#to_r) invoked on a float (0.1), and if you pass through a float
accuracy
is generally lost due to the limitations of the representation of
floating-point numbers. That’s why you get
3602879701896397/36028797018963968.

On the other hand 0.1r is safe, that is a rational literal, no float is
involved, it is exact.

On Sat, Jan 25, 2014 at 1:04 AM, Selvag R. [email protected]
wrote:

Guide me to use the Rational number in Ruby.

what is the way?

Do you have a more specific question?

On Mon, Jan 27, 2014 at 12:16 PM, Selvag R. [email protected]
wrote:

That’s fine, I trying Ruby code to store the rational number into

Postgresql, but it throwing error as invalid value for integer()
because I used column type as Integer. Which type of column (in pg)
allows that value to store?

I know it is DB related one. assist me if you faced the same case.

Postgres does not have a rational type, but the pgmp extension provides
one:

http://pgmp.projects.pgfoundry.org/mpq.html

Works like a charm.

thank for information

That’s fine, I trying Ruby code to store the rational number into
Postgresql, but it throwing error as invalid value for integer()
because I used column type as Integer. Which type of column (in pg)
allows that value to store?

I know it is DB related one. assist me if you faced the same case.