Things That Newcomers to Ruby Should Know (11/24/02)

Hi,

This is the (approximately) monthly posting of this list. I just added
minor examples to Items 11 and 17. Also note that since currently
there is some DNS problem with the “Ruby Central” site, please see the
instruction at http://www.ruby-lang.org/en/.

This list is also available in HTML format at
http://www.glue.umd.edu/~billtj/ruby.html.

Regards,

Bill

···

=============================================================================

               Things That Newcomers to Ruby Should Know

Table of Contents

 * Resources

1. Using warnings
2. Interactive shell
3. On-screen documentation
4. Class#method notation
5. Getting characters from a String
6. Array and Hash default values
7. Mutable Hash keys
8. Reading numerals from a file
9. Pre/Post Increment/Decrement Operators
  1. Lexical scoping in blocks
  2. Two sets of logical operators
  3. The === operator and case statements
  4. White space
  5. The “dot” method call operator
  6. Range objects
  7. Boolean values
  8. Variables, references, and objects
  9. Deep copy
  10. Class variables
  11. Substituting Backslashes
 * Things That Are Good to Know :-)
 _________________________________________________________________

 * Resources:
      + HOME PAGE: http://www.ruby-lang.org/en/
      + FAQ: http://www.rubycentral.com/faq/ (original) or
        http://www.rubygarden.org/iowa/faqtotum (latest)
      + PITFALL:
        http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=pitfall
      + ONLINE TUTORIAL/DOC/BOOK: http://www.rubycentral.com/book/
      + VERY USEFUL HINTS:
           o "Programming Ruby" book by David Thomas and Andrew Hunt,
             "When Trouble Strikes" Chapter, "But It Doesn't Work"
             Section
           o "The Ruby Way" book by Hal Fulton, Chapter 1: "Ruby In
             Review"

1. Use "ruby -w" instead of simply "ruby" to get helpful warnings. If
   not invoking "ruby" directly, you can set the environment variable
   RUBYOPT to 'w':
      + win32:
        C:\> set RUBYOPT=w
            or
        pressing F5 (to execute) in the Scite editor will give you 
        warnings
        (and F4 will position at problematic line).
      + unix:
        sh# export RUBYOPT="w"
            or
        csh# setenv RUBYOPT "w"

2. Ruby has an interactive shell; try to invoke the command "irb"
   instead of "ruby". "irb" is best used for experimenting with the
   language and classes; you may try things out in this environment
   before putting them in your programs.

3. For convenient on-screen Ruby documentation, consider to use (and
   install, if necessary) "ri"
   (http://www.pragmaticprogrammer.com/ruby/downloads/ri.html).
   For example, too see the methods of the File class, run "ri File".
   To read about its open method, type "ri File.open".

4. The notation "Klass#method" in documentation is used only to
   represent an "instance method" of an object of class Klass; it is
   not a Ruby syntax at all. A "class method" in documentation, on
   the other hand, is usually represented as "Klass.method" (which is
   a valid Ruby syntax).

5. The String#[Fixnum] method does not return the "character" (which
   is a string of length one) at the Fixnum position, but instead the
   ASCII character code at the position (however, this may change in
   the future). Currently, to get the character itself, use
   String#[Fixnum,1] instead.
   Furthermore, there are additional ASCII conversion methods such as
      + Integer#chr to convert from the ASCII code to the character
        65.chr    # -> "A"
      + ?chr to convert from the character to the ASCII code
        ?A        # -> 65
   Using these properties, for example, some ways to get the last
   character in a string is by writing "aString[-1, 1]" or
   "aString[-1].chr".

6. Array.new(2, Hash.new) # -> [{}, {}]
   but the two array elements are identical objects, not independent
   hashes. To create an array of (independent) hashes, use the "map"
   or "collect" method:
        arr = (1..2).map {Hash.new}
   Similarly, when creating a hash of arrays, probably the following
   is not the original intention:
        hsh = Hash.new([])
        while line = gets
          if line =~ /(\S+)\s+(\S+)/
            hsh[$1] << $2
          end
        end
        puts hsh.length    # -> 0
   One correct and concise way is to write "(hash[key] ||= []) <<
   value", such as
        hsh = Hash.new
        while line = gets
          if line =~ /(\S+)\s+(\S+)/
            (hsh[$1] ||= []) << $2
          end
        end

7. Be careful when using "mutable" objects as hash keys. To get the
   expected result, call Hash#rehash before accessing the hash
   elements. Example:
        s = "mutable"
        arr = [s]
        hsh = { arr => "object" }
        s.upcase!
        p hsh[arr]    # -> nil (maybe not what was expected)
        hsh.rehash
        p hsh[arr]    # -> "object"

8. After reading data from a file and putting them into variables,
   the data type is really String. To convert them into numbers, use
   the "to_i" or "to_f" methods. If, for example, you use the "+"
   operator to add the "numbers" without calling the conversion
   methods, you will simply concatenate the strings.
   An alternative is to use "scanf"
   (http://www.rubyhacker.com/code/scanf).

9. Ruby has no pre/post increment/decrement operator. For instance,
   x++ or x-- will fail to parse. More importantly, ++x or --x will
   do nothing! In fact, they behave as multiple unary prefix
   operators: -x == ---x == -----x == ......
  1. Beware of the lexical scoping interaction between local variables
    and block local variables. If a local variable is already defined
    before the block, then the block will use (and quite possibly
    modify) the local variable; in this case the block does not
    introduce a new scope. Example:
    (0…2).each do |i|
    puts "inside block: i = #{i}"
    end
    puts “outside block: i = #{i}” # -> undefined `i’
    On the other hand,
    i = 0
    (0…2).each do |i|
    puts "inside block: i = #{i}"
    end
    puts “outside block: i = #{i}” # -> 'outside block: i = 2’
    and
    j = 0
    (0…2).each do |i|
    j = i
    end
    puts “outside block: j = #{j}” # -> ‘outside block: j = 2’

  2. In Ruby, there are two sets of logical operators: [!, &&, ||] and
    [not, and, or]. [!, &&, ||]'s precedence is higher than the
    assignments (=, %=, ~=, /=, etc.) while [not, and, or]'s
    precedence is lower. Also note that while &&'s precedence is
    higher than ||'s, the and’s precedence is the same as the or’s. An
    example:
    a = 'test’
    b = nil
    both = a && b # both == nil
    both = a and b # both == 'test’
    both = (a and b) # both == nil

  3. In the case statement
    case obj
    when obj_1

    when obj_k

    it is the “===” method which is invoked, not the “==” method.
    Also, the order is “obj_k === obj” and not “obj === obj_k”.
    The reason for this order is so that the case statement can
    "match" obj in more flexible ways. Three interesting cases are
    when obj_k is either a Module/Class, a Regexp, or a Range:

    • The Module/Class class defines the “===” method as a test
      whether obj is an instance of the module/class or its
      descendants (“obj#kind_of? obj_k”).
    • The Regexp class defines the “===” method as a test whether
      obj matches the pattern (“obj =~ obj_k”).
    • The Range class defines the “===” method as a test whether
      obj is an element of the range (“obj_k.include? obj”).
  4. It is advisable not to write some white space before the opening
    ’(’ in a method call; else, Ruby with $VERBOSE set to true may
    give you a warning.

  5. The “dot” for method call is the strongest operator. So for
    example, while in some other languages the number after the dot in
    a floating point number is optional, it is not in Ruby. For
    example, “1.e6” will try to call the method “e6” of the object 1
    (which is a Fixnum). You have to write “1.0e6”.
    However, notice that although the dot is the strongest operator,
    its precedence with respect to method name may be different with
    different Ruby versions. At least in Ruby 1.6.7, “puts
    (1…3).length” will give you a syntax error; you should write
    "puts((1…3).length)" instead.

  6. “0…k” represents a Range object, while “[0…k]” represents an
    array with a single element of type Range. For example, if
    [0…2].each do |i|
    puts "i = #{i}"
    end
    does not give what you expect, probably you should have written
    (0…2).each do |i|
    puts "i = #{i}"
    end
    or
    0.upto(2) do |i|
    puts "i = #{i}“
    end
    instead. Notice also that Ruby does not have objects of type
    "Tuple” (which are immutable arrays) and parentheses are usually
    put around a Range object for the purpose of precedence grouping
    (as the “dot” is stronger than the “dot dot” in the above
    example).

  7. In Ruby, only false and nil are considered as false in a Boolean
    expression. In particular, 0 (zero), “” or ‘’ (empty string), []
    (empty array), and {} (empty hash) are all considered as true.

  8. Ruby variables hold references to objects and the = operator
    copies the references. Also, a self assignment such as a += b is
    actually translated to a = a + b. Therefore it may be advisable to
    be aware whether in a certain operation you are actually creating
    a new object or modifying an existing one.
    For example, string << “another” is faster than string +=
    “another” (no extra object creation), so you would be better off
    using any class-defined update-method (if that is really your
    intention), if it exists. However, notice also the "side effects"
    on all other variables that refer to the same object:
    a = 'aString’
    c = a
    a += ’ modified using +='
    puts c # -> “aString”

     a = 'aString'
     c = a
     a << ' modified using <<'
     puts c    # -> "aString modified using <<"
    
  9. There is no standard, built-in deep copy in Ruby. One way to
    achieve a similar effect is by serialization/marshalling. Because
    in Ruby everything is a reference, be careful when you want to
    "copy" objects (such as by using the dup or clone method),
    especially for objects that contain other objects (such as arrays
    and hashes) and when the containment is more than one level deep.

  10. A class variable is in general per-hierarchy, not per-class (i.e.,
    a class variable is “shared” by a parent and all of its
    descendants, in addition to being shared by all instances of that
    class). One subtle exception is if a child class creates a class
    variable before its parent does. For example, when a parent
    creates a class variable first:
    class Base
    def initialize; @@var = ‘base’; end
    def base_set_var; @@var = ‘base’; end
    def base_print_var; puts @@var; end
    end

     class Derived < Base
       def initialize;        super; @@var = 'derived'; end #notice
       def derived_set_var;   @@var = 'derived';        end
       def derived_print_var; puts @@var;               end
     end
    
     d = Derived.new
     d.base_set_var;    d.derived_print_var    # -> 'base'
                        d.base_print_var       # -> 'base'
     d.derived_set_var; d.derived_print_var    # -> 'derived'
                        d.base_print_var       # -> 'derived'
    

    In the above code, the class variable @@var is indeed “shared” by
    the Base and Derived classes. However, now see what happens when a
    child class creates the variable first:
    class Base
    def initialize; @@var = ‘base’; end
    def base_set_var; @@var = ‘base’; end
    def base_print_var; puts @@var; end
    end

     class Derived < Base
       def initialize;        @@var = 'derived'; super; end #changed
       def derived_set_var;   @@var = 'derived';        end
       def derived_print_var; puts @@var;               end
     end
    
     d = Derived.new
     d.base_set_var;    d.derived_print_var    # -> 'derived'
                        d.base_print_var       # -> 'base'
     d.derived_set_var; d.derived_print_var    # -> 'derived'
                        d.base_print_var       # -> 'base'
    

    In this case, the parent and child classes have two independent
    class variables with identical names.

  11. Substituting backslashes may be tricky. Example:
    str = ‘a\b\c’ # -> a\b\c
    puts str.gsub(/\/,’\\’) # -> a\b\c
    puts str.gsub(/\/,’\\\’) # -> a\b\c
    puts str.gsub(/\/,’\\\\’) # -> a\b\c
    puts str.gsub(/\/) { ‘\\’ } # -> a\b\c
    puts str.gsub(/\/, ‘&&’) # -> a\b\c

Things That Are Good to Know :slight_smile:

a. In Ruby the "self assignment operator" goes beyond "+=, -=, *=,
   /=, %=". In particular, operators such as "||=" also exist (but
   currently not for a class variable if it is not yet defined; this
   may change in the future). Please see Table 18.4 in the
   "Programming Ruby" book for the complete list.

b. For a "cookbook" with many algorithm and code examples, consider
   "PLEAC-Ruby" (http://pleac.sourceforge.net/pleac_ruby/t1.html).

c. For extensive numerical computations, consider "Numerical Ruby"
   (http://www.ir.isas.ac.jp/~masa/ruby/index-e.html).

d. For (numerical) arrays which consume a large amount of memory
   and/or CPU time, consider "NArray" which is part of the Numerical
   Ruby (http://www.ir.isas.ac.jp/~masa/ruby/na/SPEC.en).

e. For speeding up some parts of your Ruby code by writing them in C,
   consider "Inline" (http://sourceforge.net/projects/rubyinline/).

f. For Ruby to C translation, consider "rb2c"
   (http://easter.kuee.kyoto-u.ac.jp/~hiwada/ruby/rb2c/).

g. For Ruby and C/C++ integration, consider "SWIG"
   (http://www.swig.org/).

h. For Ruby and Java integration, consider "JRuby"
   (http://jruby.sourceforge.net/).

i. For embedding Python in Ruby, consider "Ruby/Python"
   (http://www.ruby-lang.org/en/raa-list.rhtml?name=Ruby%2FPython).

j. For embedding Lua in Ruby, consider "Ruby-Lua"
   (http://ruby-lua.unolotiene.com/ruby-lua.whtm).

k. For creating a stand-alone (Windows) executable, consider "exerb"
   (http://exerb.sourceforge.jp/index.en.html).

l. For manipulating raw bits, instead of using Fixnum's, consider
   "BitVector"
   (http://www.ce.chalmers.se/~feldt/ruby/extensions/bitvector/).

 * For comments on this list, you may e-mail me directly at
   billtj@glue.umd.edu.
 _________________________________________________________________

Last updated: Nov 24, 2002.
This list itself is available at
http://www.glue.umd.edu/~billtj/ruby.html.
The plain text format is produced from the HTML format with “lynx
-dump -nolist” (and some minor editing).
_________________________________________________________________

Hi,

Based on some comments that I received, I slightly modified Items 9 and 11
and added Item i:

9. ... To increment a number, simply write x += 1.
  1. … The reason for this language design and some more examples can
    be found at
    http://www.rubygarden.org/iowa/faqtotum/abN18mrYFE49E/c/1.13.3.3.5.
i. For Ruby and Delphi integration, consider "Apollo"
   (http://www.users.yun.co.jp/~moriq/apollo/index-en.html).

These changes have been reflected in the web page.

Regards,

Bill

Howdy folks,

Newbie here… but so far liking what I see.

My first question is this :

Is there a shortcut to embed a variable String within
a regex?

Something like :
myString =~ /$(myVariable)_\d\d\d/

instead of

myString ~= Regexp.new(myVariable + ‘_\d\d\d’)

Thanks fellas.

Jason

  1. Ruby has no pre/post increment/decrement operator. For instance, x++
    or x-- will fail to parse.

Why is that? x++ and x-- are very convenient. I sort of understand why
++x and --x don’t exist. But why can’t numbers have a “++” and “–”
method?

Daniel.

William Djaja Tjokroaminata billtj@z.glue.umd.edu writes:

Hi,

Based on some comments that I received, I slightly modified Items 9 and 11
and added Item i:

9. ... To increment a number, simply write x += 1.
  1. … The reason for this language design and some more examples can
    be found at

    http://www.rubygarden.org/iowa/faqtotum/abN18mrYFE49E/c/1.13.3.3.5.

I’m afraid you can’t store persistent references to the online FAQ
like this: these are Iowa session references and they’re volatile. I’m
going to be rewriting Faqtotum using different technologies and
publishing the comparisons. You’ll soon be able to do something like

     http://www.rubygarden.org/iowa/faqtotum/entry_at/8/2

to reference the second entry in section 8, or

     http://www.rubygarden.org/iowa/faqtotum/entry/123

to reference the entry with ID 123, no matter where it appears in the
FAQ (so, for example, if an entry is moved between sections, the
first form will fail, but the second will not)

Cheers

Dave

Howdy folks,

Newbie here… but so far liking what I see.

My first question is this :

Is there a shortcut to embed a variable String within
a regex?

Something like :
myString =~ /$(myVariable)_\d\d\d/

myString =~ /#{myVariable}_\d\d\d/

In general, #{} evaluates a Ruby expression inside string literals.

···

----- Original Message -----
From: “Jason Persampieri” jason@persampieri.net
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Monday, November 25, 2002 4:27 PM
Subject: Combining variables and Regex’s

instead of

myString ~= Regexp.new(myVariable + ‘_\d\d\d’)

Thanks fellas.

Jason

Is there a shortcut to embed a variable String within
a regex?

Something like :
myString =~ /$(myVariable)_\d\d\d/

I think that

myString =~ /#{myVariable}_\d\d\d/

does what you want.

Daniel.

Tue, 26 Nov 2002 06:30:36 +0900: Daniel Carrera (Daniel Carrera
dcarrera@math.umd.edu):

  1. Ruby has no pre/post increment/decrement operator. For instance,
    x++ or x-- will fail to parse.

Why is that? x++ and x-- are very convenient. I sort of understand
why++x and --x don’t exist. But why can’t numbers have a “++” and
“–” method?

I don’t see it as that big of a deal. “very convenient”? How
about “marginally convenient”? Really, how much more convenient is this:

x++

over this?

x += 1

By my count, it’s two spaces, a shift key, and an extra character. And
you can drop the spaces if you’d like. But the second form certainly
seems more clear to me, and I even use +=1 over ++ in /all/ languages I
code in.

If Ruby supported neither ++ /nor/ +=, then it’d get a little annoying,
as you’d have to x = x + 1, but I really just don’t see what makes it
“very convenient”.

···


< There is a light that shines on the frontier >
< And maybe someday, We’re gonna be there. >
< Rando Christensen / rando@babblica.net >

Hi Dave,

Then I will change the reference when the new format is available. Just
please let us know when the “absolute” (second) form is working. Thanks
for pointing this out.

Regards,

Bill

···

Dave Thomas Dave@pragmaticprogrammer.com wrote:

I’m afraid you can’t store persistent references to the online FAQ
like this: these are Iowa session references and they’re volatile. I’m
going to be rewriting Faqtotum using different technologies and
publishing the comparisons. You’ll soon be able to do something like

     http://www.rubygarden.org/iowa/faqtotum/entry_at/8/2

to reference the second entry in section 8, or

     http://www.rubygarden.org/iowa/faqtotum/entry/123

to reference the entry with ID 123, no matter where it appears in the
FAQ (so, for example, if an entry is moved between sections, the
first form will fail, but the second will not)

“Gennady F. Bystritsky” gfb@tonesoft.com writes:

myString =~ /#{myVariable}_\d\d\d/

In general, #{} evaluates a Ruby expression inside string literals.

but // is a regex delimiter, not a string, right? Is this just a case
where Ruby is like Perl, and regexes are double-quotish by default?

-=Eric

···


Come to think of it, there are already a million monkeys on a million
typewriters, and Usenet is NOTHING like Shakespeare.
– Blair Houghton

Okay, "very convenient" was a stupid way of putting it. I like "x++"
because it makes me think about the code I'm wirting differently. It's
not because I'm typing less. It's because I use ++ in some circunstances
and += in others in such a way that I feel my code sends a clearer
message.
I use ++ for counters and indices, and += when the numerical value has a
greater significance (even if I end up writing "+= 1").

So, I'd like to replace what I said by "I like it a lot".

Still, why doesn't Ruby include it? You can hardly say it's confusing.

Daniel.

Rando Christensen rando@babblica.net writes:

x++
over this?
x += 1

By my count, it’s two spaces, a shift key, and an extra character.

On an expression that would otherwise be three characters long, that’s
quite a high percentage, no?

···


We use Linux for all our mission-critical applications. Having the source code
means that we are not held hostage by anyone’s support department.
(Russell Nelson, President of Crynwr Software)

Scripsit ille aut illa Rando Christensen rando@babblica.net:

Tue, 26 Nov 2002 06:30:36 +0900: Daniel Carrera (Daniel Carrera
dcarrera@math.umd.edu):

  1. Ruby has no pre/post increment/decrement operator. For instance,
    x++ or x-- will fail to parse.

Why is that? x++ and x-- are very convenient. I sort of understand
why++x and --x don’t exist. But why can’t numbers have a “++” and
“–” method?

I don’t see it as that big of a deal. “very convenient”? How
about “marginally convenient”? Really, how much more convenient is this:

x++

over this?

x += 1

By my count, it’s two spaces, a shift key, and an extra character.

100%.

In C++, for example, I mostly prefer

++i

over

i++

because i++ works slightly differently (it saves the value of i,
increases i by one and returns the saved value). Whenever I write “i++”,
I use the feature that i is “first returned, then incremented”. Example:

a[i++] = ‘h’;
a[i++] = ‘e’;
a[i++] = ‘l’;
a[i++] = ‘l’;
a[i++] = ‘o’;

++i and i+=1 are semantically the same, but i++ and i+=1 aren’t. i++ is
roughly equivalent to (i+=1)-1.

But as already written: the worst thing is that “++x” doesn’t cause an
error, only a warning.

···


[mpg123d] Just playing: …/albums/shamrock/14 lookin’ for love.mp3
A remarkable, elegant little C function was written to implement I-TAG
processing, but it has too many lines of code to include in this margin [11].
RFC 2795

Hi,

···

In message “Re: Combining variables and Regex’s” on 02/11/26, Eric Schwartz emschwar@fc.hp.com writes:

In general, #{} evaluates a Ruby expression inside string literals.

but // is a regex delimiter, not a string, right? Is this just a case
where Ruby is like Perl, and regexes are double-quotish by default?

In general, #{} evaluates a Ruby expression inside “double quotish
string-like” literals, such as double quoted strings (“”), backquoted
command input (``), and regexps (//).

						matz.

Hi,

I think this subject has been discussed extensively in the past. One of
the latest discussions is http://www.ruby-talk.org/52944 (and all the
other discussions surrounding it). But if someone can give me an
authoritative reference regarding the reason why ‘++’ is not provided in
Ruby, I will include it in the list.

Regards,

Bill

···

Daniel Carrera dcarrera@math.umd.edu wrote:

Okay, “very convenient” was a stupid way of putting it. I like “x++”
because it makes me think about the code I’m wirting differently. It’s
not because I’m typing less. It’s because I use ++ in some circunstances
and += in others in such a way that I feel my code sends a clearer
message.
I use ++ for counters and indices, and += when the numerical value has a
greater significance (even if I end up writing “+= 1”).

So, I’d like to replace what I said by “I like it a lot”.

Still, why doesn’t Ruby include it? You can hardly say it’s confusing.

Daniel.

Rando Christensen rando@babblica.net writes:

x++
over this?
x += 1

By my count, it’s two spaces, a shift key, and an extra character.

On an expression that would otherwise be three characters long, that’s
quite a high percentage, no?

And given that the concept of ‘x++’ is very rarely needed in a Ruby program,
having iterators instead of for-loops, those extra three characters are
actually a very small percentage, amortised over the entire program.

Gavin

···

From: “Simon Cozens” simon@simon-cozens.org

And given that the concept of ‘x++’ is very rarely needed in a Ruby program,
having iterators instead of for-loops, those extra three characters are
actually a very small percentage, amortised over the entire program.

Regardless, is there a reason not to have ‘++’?
It’s the kind of shortcut that many programmers expect and I just can’t
think of any reason not to have it. Following the principle of Least
Surprise, I’d expect to find this feature, unless there is a good reason
to avoid it.

Daniel.

Hi –

I think this subject has been discussed extensively in the past. One of
the latest discussions is http://www.ruby-talk.org/52944 (and all the
other discussions surrounding it). But if someone can give me an
authoritative reference regarding the reason why ‘++’ is not provided in
Ruby, I will include it in the list.

From http://www.ruby-talk.org/2710, by Matz:

(1) ++ and – are NOT reserved operator in Ruby.

(2) C’s increment/decrement operators are in fact hidden assignment.
They affect variables, not objects. You cannot accomplish
assignment via method. Ruby uses +=/-= operator instead.

(3) self cannot be a target of assignment. In addition, altering
the value of integer 1 might cause severe confusion throughout
the program.

David

···

On Tue, 26 Nov 2002, William Djaja Tjokroaminata wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

And given that the concept of ‘x++’ is very rarely needed in a Ruby
program,
having iterators instead of for-loops, those extra three characters are
actually a very small percentage, amortised over the entire program.

Regardless, is there a reason not to have ‘++’?
It’s the kind of shortcut that many programmers expect and I just can’t
think of any reason not to have it. Following the principle of Least
Surprise, I’d expect to find this feature, unless there is a good reason
to avoid it.

Daniel.

In other languages, ++/-- is a lot more than just ‘x = x + 1’. It’s the
pre-/post- increment/decrement operator. That is:

int x = [5,6,7,8,9];
int a = 1;
x[++a]; // → 7; a == 2
x[a++]; // → 7; a == 3
x[a]; // → 8; a == 3

Ruby can’t/won’t replicate this behaviour, so swiping the operators would
mislead. I don’t know what a[x += 1] does in Ruby, and I’m not going to ask.

Gavin

···

From: “Daniel Carrera” dcarrera@math.umd.edu

dblack@candle.superlink.net wrote:

From http://www.ruby-talk.org/2710, by Matz:
(deleted)

Thanks, David. I have added it to the list.

Regards,

Bill