Robert K. wrote in post #1089807:
That was just for demonstration purposes.
Understood.
There’s still a better way to do that then just match everything non
whitespace. How would you parse “:s9d2++*3h43” as a number?[“1 3/4”, “5”, ‘-23’, ‘-23 -4/4’].each do |s|
puts sif %r{\A([-+]?\d+)(?:\s+([-+]?\d+)/(\d+))?\z} =~ s
w, n, d = $2 ? [$1.to_i, $2.to_i, $3.to_i] : [1, $1.to_i, 0]
printf “%4d %4d %4d\n”, w, n, d
else
$stderr.puts “No match #{s}”
end
end
I like that, because it introduces to_i during capture, which was what I
was also trying to figure out. I have already modified my regex to
something similar to yours.
Btw, did I mention that I find your variable assignment weird? I’d
rather do[“1 3/4”, “5”, ‘-23’, ‘-23 -4/4’].each do |s|
puts sif %r{\A([-+]?\d+)(?:\s+([-+]?\d+)/(\d+))?\z} =~ s
w, n, d = $2 ? [$1.to_i, $2.to_i, $3.to_i] : [$1.to_i, 0, 1]
printf “%4d %4d %4d\n”, w, n, d
else
$stderr.puts “No match #{s}”
end
end
I will have to search for “weird” in recent posts. haha! I do not
doubt it, but for my C++ to Perl to Ruby translation, it was
seamless.
I don’t have the time right now but you should definitively use class
Rational. Also your parsing of the command line could be better:do
print "Fraction 1: "
input = gets or break
f1 = parse_fraction(input)print "Fraction 2: "
input = gets or break
f2 = parse_fraction(input)print "Command: "
input = gets or breakcase input
when “A”
puts f1 + f2
when “S”
puts f1 - f2
…
else
abort “Invalid command: #{input}”
endend until cmd == “Q”
puts “Quitting”
You should also not implement #to_string but rather #to_s and then use
string interpolation for constructing your outputs.Kind regards
robert
As I stated as an edit in a previous post, this started as an assignment
to create a C++ class that handles fractions, so I then created a Perl
“class”, and now a Ruby class. So, using “require rational”, or “use
bigrat” in Perl, would have defeated the purpose. I do plan on learning
more about Ruby, and Perl, add-ons.
Thank you all for the input! I really appreciate being able to post
code and have quality responses. I am transitioning from a career
(nearly 20 years) in IT, to going to school to get my BS in CS, to then
continue as a programmer.
I’ll try not to be a stranger as long as my code is to be considered
strange. 
