Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,143,242 members, 7,780,484 topics. Date: Thursday, 28 March 2024 at 03:18 PM

Working With Fractions In Ruby - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Working With Fractions In Ruby (793 Views)

Which Software Engineering Maths Are You Working With? / Python Or Ruby For First Programming Learning / I Am A Programmer But I Am Interested In Ruby (2) (3) (4)

(1) (Reply)

Working With Fractions In Ruby by harryobas: 9:28am On May 18, 2018
Developers typically represent numbers as either integers or floats. But occasionally, neither of these is a good choice. What if we want to represent a number as an exact fraction like 2/3 instead of an approximation like 0.667? In that case, our best choice is neither an integer, nor a float, but a "rational." Here's how rationals work in Ruby:

You can create rational numbers in many ways

3/2r
1.5.to_r
"3/2".to_r
Rational(3, 2)

Rational math produces rational results

2/3r + 1/3r => (1/1)
2/3r * 1/3r => (2/9)
2/3r / 1/3r => (2/1)

Happy coding smiley

(1) (Reply)

I Want To Create A Blog / Get A Verified Paypal Account And Also Learn How To Cash It. / Html Expert Needed

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 5
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.