Perl to Ruby: regex captures to assignment

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 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 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 s

if %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 break

case input
when “A”
puts f1 + f2
when “S”
puts f1 - f2

else
abort “Invalid command: #{input}”
end

end 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. :slight_smile:

dbuckhal what about this?

w,n,d = 1,frac,0 unless
%r{(?:(?[-]?\d+)\s*)??(?[-]?\d+)/(?\d+)}xms =~ frac
w,n,d = w.to_i,n.to_i,d.to_i

with that you do not need the $vars

7stud – wrote in post #1089801:

By the way, if you haven’t played with Rubular, you
should
give it a try:

http://rubular.com/

I have found that. Good tool to use.

Also, I am still trying to wrap my head around the line terminating
error I showed you. I want to try other scenarios besides conditional
operators to see what happens.

Lastly, I reduced my assignment statement to two lines:

%r{(?:([-]?\d+)\s*)??([-]?\d+)(/)(\d+)}xms =~ frac
w, n, d = $3 ? [$1.to_i, $2.to_i, $4.to_i] : [1, frac.to_i, 0]

… which adds the slash check, rather than using a separate regex.
Probably still “weird”, but that’s ok. :slight_smile:

I think I need to start a new thread with new material. 20+ entries is
probably enough. For now, I’m on chapter nine of “The Ruby P.ming
Language”, which is an in-depth tour of Ruby syntax. Good stuff.

On Sat, 22 Dec 2012 08:40:58 +0100, 7stud – [email protected]
wrote:

Explain in detail what do you think a \ at the end of the line does?

It allows one to continue a line that would otherwise be terminated.
Contrived example:

a = 5

  • 2
    puts a

=> 5

a = 5 \

  • 2
    puts a

=> 7

It wasn’t necessary in OP’s example, but I also think it should work
there.

Also, I am still trying to wrap my head around the line terminating
error I showed you.

Explain in detail what you think a \ at the end of the line does? Well,
maybe we need to get more basic than that: Do you know what a newline
is?

On Fri, Dec 21, 2012 at 7:19 PM, Derrick B. [email protected]
wrote:

Robert K. wrote in post #1089807:

$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.

:slight_smile: What I meant by weird was that I would have the first variable
always store the integer number, the second the numerator and the
third the denominator. With your numbering scheme you need to
evaluate the third value against 0 to detect what kind of number you
have. With my scheme you can treat all parsed input equally and you
won’t have a division by zero (unless the user entered 0 as last
number).

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.

Ah, yes of course that makes a whole lot of sense. I must have
forgotten in between.

Btw, I have a blog posting about creating numerical classes in Ruby:
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html

You might want to read the previous article first:
http://blog.rubybestpractices.com/posts/rklemme/018-Complete_Class.html

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.

Good! Please make sure that you do not miss the part about algorithms
and data structures. I consider that one of the more important parts
in CS.

I’ll try not to be a stranger as long as my code is to be considered
strange. :slight_smile:

:slight_smile:

Kind regards

robert

Robert K. wrote in post #1089946:

Good! Please make sure that you do not miss the part about algorithms
and data structures. I consider that one of the more important parts
in CS.

Yes, Data Structure out of the way (B+), and Algorithms next quarter,
along with OOP design, Systems Programming, and 15lbs of stress to
accumulate. :smiley:

Derrick B. wrote in post #1089954:

I so also understand that the ‘’ is an escape character

Okay. Now what does this produce:

“\n”

7stud – wrote in post #1089925:

Also, I am still trying to wrap my head around the line terminating
error I showed you.

Explain in detail what you think a \ at the end of the line does? Well,
maybe we need to get more basic than that: Do you know what a newline
is?

My understanding, from a C/C++ background, is that the ‘’ allows for
continuation of the current line. Combine that with my knowledge of
comments (// and /* */ in C/C++) should allow for anything following
that to be “ignored”. Perl does not behave as Ruby did when I did the
very same thing. So, maybe I took my assumption of those to personal
ideas and definitions and expected too much from Ruby?

I so also understand that the ‘’ is an escape character to allow for
various things to happen: newlines, tabs, characters to have different
meanings in strings, etc…

So, please enlighten me as to your definition, or a link to an official
definition of a newline, line continuation indicator, and anything else
that would be useful.

Thanks,

Derrick

an official definition of a newline

Inside a ruby program, a newline is defined to be the string: “\n”.

However, anytime you hit in your text editor an invisible
newline is entered into the text you are typing. All text is just one
long continuous string of characters–where some of the characters may
be spaces, tabs, or newlines. But text editors do something special
when
they display a newline–they skip down to the next line to display the
text that follows a newline.

I just wanted to point out that all of 7stud’s messages (as far as I
know) in this thread have gotten truncated by the time they reached my
Gmail inbox. I’m not sure if this is a problem with Gmail or
ruby-forum.com or the list.

For instance, this is all I got for 7stud’s most recent message:

On Sat, Dec 22, 2012 at 4:52 PM, 7stud – [email protected] wrote:

an official definition of a newline

Inside a ruby program, a newline is defined to be the string: “\n”.


Posted via http://www.ruby-forum.com/.

But this shows up at http://www.ruby-forum.com/topic/4409205#new:

On Sat, Dec 22, 2012 at 7:09 PM, Eric C.
[email protected] wrote:

I just wanted to point out that all of 7stud’s messages (as far as I
know) in this thread have gotten truncated by the time they reached my
Gmail inbox.

Maybe I was exaggerating about it being “all of” them. Now that I’ve
looked I only see a few.

Derrick B. wrote in post #1089990:

Perl does just fine without the slash:

$n = ( $w == abs($w) )
    ? $n + $w * $d
    : -1 * ( $n - $w * $d ) if $d;

And you have no idea why that is? The perl parser knows that a
statement has ended when it sees a semi-colon. How does the ruby parser
know when a statement has ended?

I appreciate your effort, but am ready to move on to something
else to talk about.

Sure.

7stud – wrote in post #1090043:

And you have no idea why that is? The perl parser knows that a
statement has ended when it sees a semi-colon. How does the ruby parser
know when a statement has ended?

Ruby is similar to Python in that it uses line termination, unless you
indicate an implied line continuation.

a = b +
c

implies continuation, whereas

a = b

  • c

does not.

You can also use a semicolon in Ruby to end a statement, but usually
that is when you put multiple statements on one line.

I cannot wait to take the Compiler Design class, because these details
will be exactly what I need to take into consideration when creating my
own language parser.

Derrick B. wrote in post #1089888:
(…)

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.

Just to clear things up, since Ruby 1.9 Rational is not a gem nor in
Standard Lib, it is in Ruby core. For instance, this works without
requiring anything:

puts “1/40”.to_r * “2/3”.to_r #=> 1/60

and botp’s code runs without the require ‘rational’ on 1.9. Nothing
wrong with reinventing a wheel for learning purposes however.

7stud – wrote in post #1089965:

an official definition of a newline

Inside a ruby program, a newline is defined to be the string: “\n”.

However, anytime you hit in your text editor an invisible
newline is entered into the text you are typing. All text is just one
long continuous string of characters–where some of the characters may
be spaces, tabs, or newlines. But text editors do something special
when
they display a newline–they skip down to the next line to display the
text that follows a newline.

Thanks, but I am no longer trying to wrap my head around it. I tested
it in some C++ and Perl code, did not work, so I’m fine with proven
failed results. I only began this query because I did not understand
why Ruby would not allow a conditional to span the lines as such before
I even introduced comments:

n = ( w == w.abs ) \
    ? n + w * d
    : -1 * ( n - w * d ) if d != 0

…without putting a durn slash in the first line. Without it, I get:

./ratnum.rb:17: warning: invalid character syntax; use ?\s
./ratnum.rb:17: syntax error, unexpected ‘?’, expecting keyword_end
? n + w * d …
^
./ratnum.rb:18: syntax error, unexpected ‘:’, expecting keyword_end
: -1 * ( n - w * d ) if d != 0…
^
I do understand that line termination, or an optional semi-colon,
completes a statement in Ruby.

Perl does just fine without the slash:

$n = ( $w == abs($w) )
    ? $n + $w * $d
    : -1 * ( $n - $w * $d ) if $d;

I appreciate your effort, but am ready to move on to something else to
talk about. heh