Skip to content

Commit 2d6c355

Browse files
authored
Add Fraction Math in Ruby format (#5206)
1 parent 427022b commit 2d6c355

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

archive/r/ruby/fraction-math.rb

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
class Fraction
2+
attr_reader :numerator, :denominator
3+
def initialize (numerator, denominator)
4+
@numerator = numerator
5+
@denominator = denominator
6+
end
7+
8+
9+
def fraction_math(other_fraction, operator)
10+
num_one = Rational(@numerator, @denominator)
11+
num_two = Rational(other_fraction.numerator, other_fraction.denominator)
12+
13+
final_result = case operator
14+
when '/' then num_one / num_two
15+
when '*' then num_one * num_two
16+
when '+' then num_one + num_two
17+
when '-' then num_one - num_two
18+
else
19+
"Invalid operator"
20+
end
21+
final_result.to_s
22+
end
23+
24+
25+
# Comparison operators
26+
def ==(other)
27+
Rational(@numerator, @denominator) == Rational(other.numerator, other.denominator)
28+
end
29+
30+
def !=(other)
31+
Rational(@numerator, @denominator) != Rational(other.numerator, other.denominator)
32+
end
33+
34+
def >=(other)
35+
Rational(@numerator, @denominator) >= Rational(other.numerator, other.denominator)
36+
end
37+
38+
def <=(other)
39+
Rational(@numerator, @denominator) <= Rational(other.numerator, other.denominator)
40+
end
41+
def <(other)
42+
Rational(@numerator, @denominator) < Rational(other.numerator, other.denominator)
43+
end
44+
45+
def >(other)
46+
Rational(@numerator, @denominator) > Rational(other.numerator, other.denominator)
47+
end
48+
49+
end
50+
51+
# Command-line input
52+
if ARGV.length != 3
53+
puts "Usage: ./fraction-math operand1 operator operand2"
54+
exit
55+
end
56+
57+
input1, operator, input2 = ARGV
58+
59+
num1, den1 = input1.split('/').map(&:to_i)
60+
num2, den2 = input2.split('/').map(&:to_i)
61+
62+
fraction1 = Fraction.new(num1, den1)
63+
fraction2 = Fraction.new(num2, den2)
64+
65+
if operator == "+"
66+
puts fraction1.fraction_math(fraction2,"+")
67+
elsif operator == "-"
68+
puts fraction1.fraction_math(fraction2,"-")
69+
elsif operator == "/"
70+
puts fraction1.fraction_math(fraction2,"/")
71+
elsif operator == "*"
72+
puts fraction1.fraction_math(fraction2,"*")
73+
elsif operator == "=="
74+
puts fraction1 == fraction2 ? 1 : 0
75+
elsif operator == "!="
76+
puts fraction1 != fraction2 ? 1 : 0
77+
elsif operator == ">"
78+
puts fraction1 > fraction2 ? 1 : 0
79+
elsif operator == "<"
80+
puts fraction1 < fraction2 ? 1 : 0
81+
elsif operator == ">="
82+
puts fraction1 >= fraction2 ? 1 : 0
83+
elsif operator == "<="
84+
puts fraction1 <= fraction2 ? 1 : 0
85+
else
86+
puts "Invalid operator"
87+
end
88+
89+

0 commit comments

Comments
 (0)