Created
April 21, 2022 14:55
-
-
Save asonnleitner/41d4f97e87deab943dc68b108359054e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# static constants | |
FRACTIONS_COUNT = 2 | |
MIN_NUM = 1 | |
MAX_NUM = 9999 | |
# dynamic constants | |
CHAR_COUNT = MAX_NUM.to_s.length | |
FRACTION_DIVIDER = '-' * CHAR_COUNT | |
# helper function for getting user input | |
def get_user_input(value) | |
puts "#{value}:" | |
input = gets.chomp.to_i | |
if input < MIN_NUM || input > MAX_NUM | |
puts "You must enter a value between #{MIN_NUM} and #{MAX_NUM}." | |
get_user_input(value) | |
else | |
input | |
end | |
end | |
def pretty_s(numerator, denominator) | |
"#{ | |
numerator.to_s.rjust(CHAR_COUNT) | |
}\n#{ | |
FRACTION_DIVIDER | |
}\n#{ | |
denominator.to_s.rjust(CHAR_COUNT) | |
}" | |
end | |
class Fraction | |
def initialize(numerator, denominator) | |
@numerator = numerator | |
@denominator = denominator | |
@rational = Rational(numerator, denominator) | |
end | |
def to_s | |
"#{@numerator}/#{@denominator}" | |
end | |
def to_pretty_s | |
pretty_s(@numerator, @denominator) | |
end | |
def rational | |
@rational | |
end | |
def numerator | |
@rational.numerator | |
end | |
def denominator | |
@rational.denominator | |
end | |
end | |
class Fractions < Array | |
def initialize(count) | |
@fractions = [] | |
count.times { |i| | |
no = i + 1 | |
puts "Enter #{no}# fraction:" | |
@fractions << Fraction.new( | |
get_user_input("numerator"), | |
get_user_input("denominator") | |
) | |
puts @fractions[i].to_pretty_s | |
} | |
end | |
def fractions | |
@fractions | |
end | |
def rationals | |
@fractions.map { |f| f.rational } | |
end | |
def sum | |
result = rationals.reduce(:+) | |
puts "\nResult:" | |
pretty_s(result.numerator, result.denominator) | |
end | |
end | |
fractions = Fractions.new(FRACTIONS_COUNT) | |
puts fractions.sum | |
puts fractions.fractions | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment