[Courses] [Ruby] Lesson 0: Installing, References, and your first homework assignment

Laurel Fan laurel.fan at gmail.com
Thu Nov 17 03:23:00 EST 2005


On 11/11/05, Andrea Landaker <qirien at icecavern.net> wrote:
>
Hi Andrea!

> OK, for the next part of the homework, here's my husband's interactive
> crytpogram solver:

Looks good!  Great example of using regular expressions and the gsub
function, which Perl programmes may be interested in..

> #!/usr/bin/ruby
>
> $code = ARGV.join(' ').upcase
>
> puts $code
> print '$ '
> STDOUT.flush
> while STDIN.gets
>   if ~ /([A-Za-z]{2}).*/
>     code = $1[0..0].upcase
>     text = $1[1..1].upcase

This [0..0] stuff is necessary because $1[0] would return a character
(which is actually a number, not a String).  Telling it [0..0] gives
it a range (here, it's the range from 0 to 0, the first character to
the first character), which makes it return a String.

>     $code.gsub!(code,'!')

gsub is "global substitution" (see String documentation for more). 
What the exclamation mark does is do the gsub on $code itself (rather
than returning the result of doing gsub).  It's the same thing as:

$code = $code.gsub(code, '!')

One style note:  I would avoid using very similar variable names like
$code/code.  On the first read through I wasn't mentally pronouncing
the $, so I was very confused about what was going on.  The $ actually
means global variable, which in this case doesn't do much because you
have only one function anyway.  It's usually preferable to avoid
global variables for longer or more complicated programs.  However,
one benefit of Ruby is that if you're doing something simple enough
(like this) that OO and encapsulation won't help you, it won't get in
your way.  But using $ makes it look like Perl and we don't want that
;)

>     $code.gsub!(text,code)
>     $code.gsub!('!',text)
>   else
>     puts "Enter xY to make x -> Y"
>   end
>   puts $code
>   print '$ '
>   STDOUT.flush
> end
>
> The first line puts all the "arguments" (the cryptogram itself) into the
> global variable "code", uppercased.  It prints it out, and then takes two
> letters from the user.  The first letter goes in the local variable "code",
> and the second goes into "text".  Then, throughout the global variable
> "code", it swaps the two (using the exclamation point for an intermediary
> character).  This repeats essentially forever.

--
Laurel Fan
http://dreadnought.gorgorg.org


More information about the Courses mailing list