From: "Derrick B." Date: 2012-12-21T03:23:16+09:00 Subject: Re: Perl to Ruby: regex captures to assignment. Robert Klemme wrote in post #1089733: > > I would choose a completely different approach: I would have a single > expression for matching and decide which assignments to make based on > the value of one of the capturing groups in the conditional branch: > > ["1 3/4", "5"].each do |s| > puts s > > if %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 also spiced the regexp a bit more to be more restrictive. > I am prompting for input, so I would be parsing individual strings and not a list of them. Though I will remember that for future static testing. Also, I and using the "\S+" to handle negative rational numbers: "-1 3/4". > > If you like readability then why are you using Perl in the first place? > :-) > Because Perl is awesome! That is why I chose Ruby as my next personal choice of languages to learn. I just completed a quarter of Programming Language Concepts where I was introduced to Lisp, but was also required to use some Python. I know Python is a fascinatng language, but I am not yet a big fan of it. The final assignment was write a class to work with fractions. It started as a C++ class, then migrated to Perl (for fun), and now Ruby (more fun). I attached the two versions, Ruby and Perl. The Perl version uses a "class", also. Feel free to suggest how to make the Ruby version more Ruby-ish! My goal is to take more advantage of the OO aspects of Ruby, and not just have it look like Perl. Thanks, Derrick Attachments: http://www.ruby-forum.com/attachment/7988/ratnum.rb http://www.ruby-forum.com/attachment/7989/ratnum.pl -- Posted via http://www.ruby-forum.com/.