Another Code Example

 
   

Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents
 


Here is another example to serve as an introduction to discussing some more differences:

 

 perl -e 'while(<>){  last if /^x/; print } ; print "done\n";' ruby -e 'while gets; break if /^x/; print; end; puts "done"' 

Again, these code fragments behave essentially the same.

Loop Constructs, Conditionals, and Modifiers

It should be no surprise that Ruby has looping constructs such as while, until, and for. However, there are no braces, because braces are used in Ruby for iterator blocks that introduce a new scope. Instead, the body is delimited by the end keyword.

Loop control in Ruby is similar to Perl, except break is used in place of last. There is no continue and no goto, but you can simulate goto with continuations or catch/throw. A new keyword, retry, is useful both for making your own iterators and for recovering from an exception when used in the rescue portion of a begin/end block.

Tip

Exception information is stored in the $! variable. The $@ variable holds the stack backtrace for it.


The foreach loop from Perl is translated this way:

 

 foreach $item (@arr){  some_code }    # Perl for item in arr; some_code; end     # Ruby 

Ruby also has if/elsif/else/end, unless/else/end, and case/when/else/end. These also do not use braces.

Note

These statements evaluate the "truth value" of a given condition. Remember that "", "0", and 0 will all be true because only false and nil are false in Ruby.


Modifiers work the same way as in Perl, except there is no foreach modifier.

Blocks

Ruby has more than one kind of block. The begin/end block is most often used with rescue and ensure to handle exceptions. It lets you group statements for control, and it may also be nested. Aside from the lack of scope, it seems to be the closest thing to Perl's brace-delimited blocks because it may stand by itself, and it supports flow control, such as next.

The do/end or {} block, on the other hand, must be associated with a method (otherwise, it is treated as a hash literal). This block is both a closure and an iterator. Its parameter list is used for parallel assignment of passed arguments and is required if you plan to use themthere is no equivalent to Perl's @_ variable. Here's an example:

 

 obj.iterator_method { |x,y| statements_in_here } # associated iterator closure 

Note

Anything assignable may be put in the parameter list, including an existing variable. If it is a local variable that does not yet exist, it will be created and kept local to the block. Otherwise, it is not local to the block.


There are also built-in iterator methods such as each, loop, upto, step, and times.

Note

The Ruby do keyword is very different from Perl's do.


Regexes

Both \b and \s are interpolated differently in double quotes and in %r or // regex literals.

There is no equivalent to (?<=, (?<!, (?{}, or (?().

Ruby does not have the /s modifier, and the /m modifier works like Perl's /sm combination.

Tip

You can simulate Perl's /s with Ruby's \A and \Z, and you can simulate Perl's /m by using /m with [^\n] in place of the dot in Ruby.


There is no /g modifier. Use String#gsub for s///g and String#scan for m//g. Also, use String#index for Perl's pos(). By the way, the pound (#) notation as used here is not part of the Ruby language but is rather a bit of slang to denote an instance method as opposed to a class method. You can use \G with the scan, gsub, and index methods.

Use String#sub for s///, use // for m//, and use String#tr for tr///. Use String#tr_s for tr///s, use String#delete for something close to tr///d, and use ^ at the start of the character list for tr///c.

There is no study equivalent. Use Regexp#quote for quotemeta. There are no /c, /e, and /ee modifiers. The following translation can be used for /e:

 

 $text="lower to upper"; $text =~ s/(\w+)/uc($1)/ge;    # Perl text="lower to upper"; text.gsub!(/(\w+)/){ $1.upcase}   # Ruby 

The =~ operator is a method defined for both the Regexp and String classes, and it returns the position of the first match.

For example, the following will not assign $1 and $2 to x and y:

 

 x,y = (var =~ /(.)(.)/) 

Instead, use String#scan, which returns an array of all matches. Use a subscript to access the nth group of matches, like so:

 

 x,y = var.scan(/(.)(.)/)[0] 

Back references are available, although you are warned to be careful about quoting them properly.

The Regexp#match method produces another type of object, of class MatchData, containing more detailed results.

Output

The print method uses $_ as a default argument. See puts and p, new output methods that don't utilize $_.

Printing to a file handle is different:

 

 f = File.new("myfile.txt","w") f.print "My text here.\n" f.close 

Unlike Perl, chomp and chop do not return what was removed but rather what remains. The argument to chomp indicates what should be removed, defaulting to the current record separator.

Also, note that split also behaves slightly differently.

Special Variables

Ruby has special built-in variables inspired by Perl, but some have differing meanings. For example, $" is used for %INC, $: is used for @INC, and $* and ARGV are used for @ARGV. What's more, $@, $=, $~, $<, $>, and $; are also used differently in Ruby. You can still use $!, $&, $+, $`, $', $1..$9, $/, $\, $,, $., $0, $$, $?, and $_ pretty much the same. ENV is used for %ENV, and $0 would be used for $ARGV. There is nothing for $^-type built-ins, except you can use RUBY_PLATFORM for $^O, and you can use $-w for $^W. Also, RUBY_VERSION can be used for $]. No features in Ruby correspond to Perl's $|, %SIG, @_, $-, $#, $=, $~, $%, $:, $;, and $[. Use the m modifier for $* and use Ruby's $, for $". As with Perl, Ruby has English equivalents available for these. Information on processes accessed via Perl's $(, $), $<, and $> can be obtained from the built-in Process module's gid, egid, uid, and euid methods.

Note

Some built-in variables, such as $_ and $~, do not actually behave as globals. Also, $_ doesn't always behave as Perl's equivalent does.



   

 

 



The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net