On Feb 22, 7:12 pm, Mark Tarver <dr.mtar...@[EMAIL PROTECTED]
> wrote:
> First I've seen Ruby used. Don't understand a damn thing of
> course :),
> but 55 LOC puts it top.
>
> Mark
Symbols begin with ":".
Lists (arrays to Rubyists) are enclosed in [], but they
can be omitted sometimes, e.g.:
a = 22,33,44
"<<" appends to a list:
[6,7,8] << 9
==>[6, 7, 8, 9]
The index of the first element in a list is 0:
[6,7,8][0]
==>6
The array method ".join" is almost self-explanatory:
['tip', '-', 'top'].join
==>"tip-top"
['tip', '-', 'top'].join( '***' )
==>"tip***-***top"
Anonymous code blocks are enclosed in {..} or do ... end.
The parameters of the code block are enclosed in |...|.
In this example, the parameter is "n":
[6,7,8].map{|n| n * 2 }
==>[12, 14, 16]
In a different context {...} indicates a hash (associative
array):
h = {'foo',44, 'bar',55, 'boo',66}
==>{"boo"=>66, "foo"=>44, "bar"=>55}
It's clearer but more tedious to separate key-value pairs
with "=>":
h = {'foo'=>44, 'bar'=>55, 'boo'=>66}
==>{"boo"=>66, "foo"=>44, "bar"=>55}
Let's consider two lines:
tmp = s.scan(/you are|you're|\w+|\W+/).map{|s|
h[s] or h.invert[s] or s }
".scan" operates on the string s, producing a list of
substrings that are matched by the regular expression
"/you are|you're|\w+|\W+/". The pipe symbol "|" functions
as OR; "\w" matches a word character; "\W" matches a
non-word character. Example:
"you are willy-nilly, yes?".scan( /you are|you're|\w+|\W+/ )
==>["you are", " ", "willy", "-", "nilly", ", ", "yes", "?"]
Next, ".map" attempts to perform substitutions using the
key-value pairs of the hash "h". It makes good use of the
method ".invert", which swaps each key with its value:
{'foo',22, 'bar',33}
==>{"foo"=>22, "bar"=>33}
{'foo',22, 'bar',33}.invert
==>{33=>"bar", 22=>"foo"}


|