Recap - Fractions
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 41 of 57.
Challenge
HardComplete the value class Frac. initialize(num, den) reduces the fraction and keeps the sign on the numerator, raising ZeroDivisionError with zero denominator when den is 0. Define +, -, * and / returning new fractions (/ by a zero fraction raises ZeroDivisionError with division by zero), -@, ==, eql? and hash so equal fractions are the same Hash key, and <=> with Comparable. to_s returns 3/4, or 2 when the denominator is 1.
The supplied code reads commands: 1/2 + 1/3 (any of the four operators), neg 3/4, sort 1/2 1/3 3/4, max 1/2 2/3, uniq 1/2 2/4 1/3 (printing the count and the distinct fractions) and cmp 1/2 2/4 (printing =, < or >). Errors print their message.
Your code goes in frac.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'frac'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
def frac(text)
n, d = text.split("/").map(&:to_i)
Frac.new(n, d || 1)
end
input.each do |line|
parts = line.split
begin
case parts[0]
when "neg" then puts(-frac(parts[1]))
when "sort" then puts parts[1..].map { |t| frac(t) }.sort.join(" ")
when "max" then puts parts[1..].map { |t| frac(t) }.max
when "uniq"
distinct = parts[1..].map { |t| frac(t) }.uniq
puts "#{distinct.size}: #{distinct.join(" ")}"
when "cmp"
order = frac(parts[1]) <=> frac(parts[2])
puts ["<", "=", ">"][order + 1]
else
a = frac(parts[0])
b = frac(parts[2])
puts a.public_send(parts[1], b)
end
rescue ZeroDivisionError => e
puts e.message
end
end
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler