Ruby One-Liners


Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents

First, use the command line to get a feel for Ruby. Most of the same options from Perl are available. Here's an example:


 ruby -e '$x="hi"; print $x,"\n"; print 5+2;' 

This should look no different from what Perl allows. Our next little example does the same thing in a somewhat contrived way, to demonstrate a little of Ruby's syntax:


 ruby -e 'x=%q|hi|; print "#{ x} \n"; print x+"\n"; print 5.+(2)' 

Perl obviously won't like this, yet Ruby is perfectly fine with it. We'll explain.


The variable x is missing a prefix. In fact, Ruby does not require a prefix, and the prefixes it does allow are used for indicating scope and not data type. They are simply references to a strongly typed object, as defined by a particular class.

The $ prefix indicates global scope, not a scalar. However, nonprefixed variables starting with a lowercase letter are local in scope, and you can't refer to them until you put them in scope via assignment. There is no scope declaration via my or local, and there is no nesting or overriding of variables.


Local variable names are similar to method identifiers; when both are defined, you need to use parentheses with the method. Because using parentheses with methods is optional, there is a possibility of a mix-up.

Nonprefixed variables starting with an uppercase letter are constants and have class-wide scope. This is the only type of variable that may be accessed globally via the familiar :: scope operator, which is used to gain access inside of classes and modules. Method names do not count as variables.

The @ and @@ prefixes used inside object methods and classes denote variables belonging to a particular object or a whole class. They have nothing to do with arrays.


A variable, regardless of scoping, simply holds a reference to an object of a particular type (class). You cannot know this type by looking at the variable. It is like a Perl scalar holding a reference to a strongly typed objectwith automatic referencing and dereferencing. There is no backslash (\) operator. Assignment has the connotation of simply making a reference. There is no equivalent to "typeglobs," nor is there a central symbol table, but there are methods for accessing environment bindings and the various variables and constants they contain.


Multiple variables can hold a reference to the same object and may be used to alter the object referenced by another variable, leading to potentially surprising side effects.

Parallel assignment is controlled via the special * syntax (and the same rules also apply to parameter passing with blocks and methods). Here's an example:


 a, *b = [1, 2], "a", "b"    # a=[1,2], b=["a","b"] a, b, c = b, *a             # a=["a","b"], b=1, c=2 

Data Types

Ruby has built-in classes for nil (which tests as false), true, false, integers (including big integers), floats, strings, ranges (which are not stored in array form), arrays, hashes, regexes, files, and more.

You will have to stop using 0, "", and "0" to test for false. Instead, you will be checking against false or nil.

Use string[0,1].downcase for lcfirst, and string[0] for ord. Note the unfamiliar meaning of subscripts:


 "ABC"[0,1].downcase  # "aBC" "A"[0]               # 65 

Unlike Perl, Ruby does not automatically convert other object types when performing tasks such as concatenation. You can use the to_s method, which is usually defined for other objects, to convert them before working with them. Here's an example:


 "abc" + 123.to_s     # "a b c123" 

Ruby does not support ++ or , although there is succ, which works with both numbers and strings by default.

Arrays and hashes use different literals but the same accessor method. There is no $# feature for arrays; use -1 as the index to the last item of an array. A hash key need not be a string: The => syntax does not "stringify" the left-hand side, and "barewords" are not used in Ruby:


 arr = ["some", 123]; hsh = { "b"=>"hi", 99=>arr} arr[2] = "stuff" hsh["key"] = "value" meth {  .... }           # Method with associated block! 


nil can be used as both a key and value in a hash as well as a value in an array.

Ruby doesn't support "autovivification" for arrays, hashes, or any other indexed objects (although some people have written code to support this). Ordinarily you must assign a relevant object to a variable before accessing values. You can use the ||= syntax to assign conditionally.

File handles are taken care of by the File class.

File test operators have been implemented with the test method. Note that this method is missing Perl's -B, -t, and -T tests, and it adds ?G, ?-, ?=, ?<, and ?> . Also, ?s returns nil, not zero (if the file size is zero), and ?M returns the modification time, not the file age.


Double-quoted strings allow for escape characters, just as in Perl. Ruby does not support \l, \u, \L, \U, \E, or \Q. It does have some extras, such as "\s" (space), "\v" (vertical tab), "\C-" (same as "\c["), "\M-" (meta-x or alt-x), and "\M-\C-".


The \s in "\s" means a single space " ", but in the regexes' /\s/ and /[\s]/ it refers to the regular expression character class for whitespace.

Ruby uses %, %q, %w, %r, and %x in place of Perl's q, qq, qw, qr, and qx. Unlike Perl, Ruby still allows a space to be used as the delimiter for these.

You may also notice that string interpolation is done with the #{} syntax, but this is not just for variablesit is a general form that evaluates any expression. Perl has both ${} and @{} for more complex interpolation, but Ruby's approach to this actually allows for more concise scripts.

Ruby also has here-docs, just as Perl has. Indented here-docs are built in as a feature:


 print <<-`eos`   whois #{ gets.chomp} eos 

In the preceding example, you also see one of the handy uses of #{}.

String Operators

Next you should notice that the plus sign (+) is used in place of the dot (.) for string concatenation. As a matter of fact, the eq, ne, gt, lt, ge, le, cmp, and x operators are not used in Ruby either. Instead, use ==, !=, >, <, >=, <=, <=>, and * (no list context equivalents).

In fact, you can use these same operators (and others) for any object that defines them as a method.

Dot Syntax

Now let's look at a little code fragment: 5.+(2). This reveals two things in Ruby: + is just a method call, and . (dot) is the syntax for dispatching a method.

Numbers are also objects (instances of a class). As such, you can send method calls to them. Ruby will look in the object's class for an implementation of the method sent to it. Compare this to Perl's -> operator (not used in Ruby).

You normally have to include the dot when dispatching methods, but Ruby makes it optional for operators that are implemented as methods. However, by using the dot with numeric operators, you override the precedence rules. Here are some examples:


 5 + 2 * 3 + 1 * 4      # 15 5.+ 2.* 3.+ 1.* 4      # 19 5.+(2).*(3).+(1).*(4)  # 112 

About Command-Line Options

Most of the Perl command-line options work the same way for Ruby. There are a few things to note, however. For example, autosplit results are assigned to $F instead of Perl's @F, and there are no -D, -P, -u, -U, and -V flags. Note that -T optionally takes a value to set the safe level, -I uses $LOAD_PATH ($:) instead of @INC, and -S uses either RUBYPATH or PATH. Also, there are some additional options: -C and -X are used to change directories before executing the script, -r is used to "require" named libraries, and -K specifies a language code set.


There is a debug feature as well as an enhanced interactive mode called irb.




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 © 2008-2017.
If you may any questions please contact us: