Type:
Class

When mathn is required Rational is changed to simplify the use of Rational operations.

Normal behaviour:

1
2
Rational.new!(1,3) ** 2 # => Rational(1, 9)
(1 / 3) ** 2            # => 0

require 'mathn' behaviour:

1
(1 / 3) ** 2            # => 1/9

A rational number can be represented as a paired integer number; a/b (b>0). Where a is numerator and b is denominator. Integer a equals rational a/1 mathematically.

In ruby, you can create rational object with Rational, #to_r or rationalize method. The return values will be irreducible.

1
2
3
4
Rational(1)      #=> (1/1)
Rational(2, 3)   #=> (2/3)
Rational(4, -6#=> (-2/3)
3.to_r           #=> (3/1)

You can also create rational object from floating-point numbers or strings.

1
2
3
4
5
6
7
8
Rational(0.3)    #=> (5404319552844595/18014398509481984)
Rational('0.3'#=> (3/10)
Rational('2/3'#=> (2/3)
 
0.3.to_r         #=> (5404319552844595/18014398509481984)
'0.3'.to_r       #=> (3/10)
'2/3'.to_r       #=> (2/3)
0.3.rationalize  #=> (3/10)

A rational object is an exact number, which helps you to write program without any rounding errors.

1
2
10.times.inject(0){|t,| t + 0.1}              #=> 0.9999999999999999
10.times.inject(0){|t,| t + Rational('0.1')}  #=> (1/1)

However, when an expression has inexact factor (numerical value or operation), will produce an inexact result.

1
2
3
4
5
Rational(10) / 3   #=> (10/3)
Rational(10) / 3.0 #=> 3.3333333333333335
 
Rational(-8) ** Rational(1, 3)
                   #=> (1.0000000000000002+1.7320508075688772i)
<=>
  • References/Ruby on Rails/Ruby/Classes/Rational

rational numeric â -1, 0, +1 or nil Instance Public methods Performs comparison

2025-01-10 15:47:30
round
  • References/Ruby on Rails/Ruby/Classes/Rational

rat.round â integerrat.round(precision=0) â rational Instance Public methods

2025-01-10 15:47:30
json_create
  • References/Ruby on Rails/Ruby/Classes/Rational

json_create(object) Class Public methods

2025-01-10 15:47:30
fdiv
  • References/Ruby on Rails/Ruby/Classes/Rational

rat.fdiv(numeric) â float Instance Public methods Performs division and returns

2025-01-10 15:47:30
to_r
  • References/Ruby on Rails/Ruby/Classes/Rational

rat.to_r â self Instance Public methods Returns self.

2025-01-10 15:47:30