From b373c7b7585294cda22f0a0e78b9d59c9ba6108d Mon Sep 17 00:00:00 2001 From: Tim Craft Date: Tue, 22 Oct 2024 11:02:50 +0100 Subject: [PATCH] Add Rational#as_percentage_of method --- lib/percentage.rb | 4 ++++ spec/percentage_spec.rb | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/lib/percentage.rb b/lib/percentage.rb index 329ee6c..f8e3218 100644 --- a/lib/percentage.rb +++ b/lib/percentage.rb @@ -150,6 +150,10 @@ def to_percentage def percent_of(n) n * Percentage(self) end + + def as_percentage_of(n) + Percentage.new(self / n) + end end class BigDecimal diff --git a/spec/percentage_spec.rb b/spec/percentage_spec.rb index ad1c392..32dff49 100644 --- a/spec/percentage_spec.rb +++ b/spec/percentage_spec.rb @@ -480,6 +480,15 @@ expect(Rational(90).percent_of(Rational(150, 2))).to eq(Rational(135, 2)) end end + + describe '#as_percentage_of' do + it 'returns a percentage object with the value of the decimal divided by the argument' do + percentage = Rational(50).as_percentage_of(Rational(100)) + + expect(percentage).to be_a(Percentage) + expect(percentage.value).to eq(Rational(1, 2)) + end + end end RSpec.describe BigDecimal do