₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,330,913 members, 8,447,717 topics. Date: Saturday, 18 July 2026 at 08:13 PM

Toggle theme

Working With Fractions In Ruby - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingWorking With Fractions In Ruby (878 Views)

1 Reply

Working With Fractions In Ruby by harryobas(op): 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

Which Software Engineering Maths Are You Working With?Python Or Ruby For First Programming LearningI Am A Programmer But I Am Interested In Ruby234

Vacancy (part Time Web Designer And Front End/back End Programmer)Need A Web Designer Or Web Developer?In Need Of Someone Good At Consuming Web Services - SOAP, WSDL