[FAQ] [Revised again] What are the non-alphanumerical symbols in Ruby code?

Folks,

I’ve used Austin’s complete response, because it seems complete and is well
organised. It may be a bit too much information for the FAQ, but it’s good for
now. Eventually, I hope that information like this can be included in the Ruby
distribution.

The operators in the text below are not universally quoted, so I’ll work on
that, but can anybody pick any more holes?

Anyway, here it is.

···

Q. What are the non-alphanumerical symbols in Ruby code?

A.

<=> <= < >= > == !=

1.  Relational operators, used to determine the relative equality
    of values.  All of these symbols, excepting "!=", are defined
    as methods on classes.  The most common way of implementing
    these values is through the [Comparable] mixin, where it is
    only necessary to define "<=>" (which returns -ve, 0, or +ve
    to indicate comaprison).  All other relational operators, if
    defined manually, must return a boolean value (either true or
    false).  The "!=" operator is special syntax in the
    interpreter, such that "a != b" really means "!(a == b)".

2.  The "<" operator also means class inheritance, such that in
    the following example, a Car inherits from Vehicle.

      class Car < Vehicle; end
      • / % **
    1. Binary arithmetic operators representing addition (3 + 2),
      subtraction (3 - 2), multiplication (3 * 2), division (3 /
      2), modulus (integer division remainder; 3 % 2 is 1), and
      exponentiation (3 ** 2 is 9). “**” has the highest
      precedence, followed by “*”, “/”, and “%”, and finally "+"
      and “-”. All of these operators are methods.

    2. Unary plus and minus (+3, -2). Unary plus and minus have
      higher precedence than “*”, “%”, and “/”, but lower precedence
      than “**”. These are methods (+@ and -@, respectively).

~ << >> & ^ |

1.  "<<" most often means that a "here" document follows, e.g.:

      puts <<EOS
        This is a here document.
      EOS

2.  "<<" also creates a new class based on a particular object.
    These object-specific classes are called 'singleton classes'.
    In the example below, only the Car object referred to by
    "camaro" will have the method "has_flames?".

      camaro = Car.new
      class << camaro
        def has_flames?
          true
        end
      end

3.  Binary (bitwise) operators.  "~" returns the bitwise
    complement of the value (~2 is -3); "<<" and ">>" shift the
    bits of the value left and right by the specified number of
    bits (2 << 2 is 8 >> 2).  "&", "^", and "|" are bitwise "and"
    and exclusive and regular "or" operators.

===

Case comparison operator.  Used to select branches in case
statements.  In the following code, "/pattern/ === string" is
implicitly called.

  case string
    when /pattern/ then ...
  end

… …

Range defnitions.  ".." ranges are end-inclusive; "..." ranges are
end-exclusive.  Examples:

  0...10
  'a'..'z'

: ?: ::

1.  :name is a Symbol.  Most often used as a parameter to various
    methods in the Module class, (e.g., public, private,
    protected, attr_reader, attr_accessor, etc.).  Symbols are
    immutable, immediate value strings.

2.  ?: is the ternary operator:

         message = error ? error.to_s : "Everything's fine"

3.  :: resolves scope.  ::Foo refers to a constant Foo at the top
    level; Net::Ftp refers to a constant Ftp in the module (or
    class) Net.  In this case, the constant Ftp is another class.

[]

1.  Array definition, as in:

         ndays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]

2.  References an element of a collection - in particular, arrays
    and hashes.  This is a method call, defined as [](x).

         ndays[1]  == 28
         ndays[-3] == 31

{} =>

Hash definition, most often used with "=>".  Can be used in one of
two ways.  The examples below will result in the same key/value
pairs.  "=>" explicitly relates a key to a value; if => is not
used, then pairs are joined.  An odd number of values will throw
an error, regardless of which method is used.  The two methods may
not be mixed.

         { 1, 2, 3, 4, 5, 6 }
         { 1 => 2, 3 => 4, 5 => 6 }

!

Logical negation.  Turns "false" to "true" and "true" to "false".

method? method!
An optional but useful naming scheme for some methods. The symbol
is actually part of the method name. In general:
method! changes the object (e.g. String.gsub!)
method? returns boolean (e.g. Array.empty?)

=~ !~ // %r{}

Regular expression handling.  "=~" is a method, "!~" is special
syntax for "!(=~)", like "!=".  // and %r{} have the same effect
in defining a regular expression.  %r{} can be represented with
other characters.  All of the following represent the same regular
expression.  Note that if the first character following "%r" is
part of a matching pair ((), <>, [], {}), then the second
character must be the matching character; otherwise, the two
characters must be the same.

         /\d+/
         %r{\d+}
         %r/\d+/
         %r@\d+@
         %r(\d+)

#{}

String expression substitution.  #{expr} substitutes the value of
expr in a double-quoted string (including regular expressions and
command strings).  This can only be done with {}.

%q{} %Q{} %{}

Quotes, expressed another way.  %q{} is equivalent to '' and has
all the same semantics (no substitution excepting \\ to \ and \'
to ').  %Q{} and %{} are equivalent to "" and have the same
semantics (full substitution, including expression substitution
with #{}).  As with regular expressions, the {} in %q{} or %Q{}
can be represented with other characters.

%w{}

This will create an array from the string within by splitting
the string on spaces.  The string is treated as a single-quoted
string.

         dayabbrev = %w[Sun Mon Tue ...]
         dayabbrev == ["Sun", "Mon", "Tue", "..."]

%x{} ``

A command string.  Try this in irb:
   files = `ls`             # Unix
   files = `dir /w`         # Windows

[…] Anyway, here it is. […]

I straight away realised I had forgot to define ?c notation and @ and @@.

I’ll get to these but it doesn’t require a posted update.

Gavin

···

From: “Gavin Sinclair” gsinclair@soyabean.com.au

Replying to myself again: I’ve put the text at
http://www.rubygarden.org/ruby?FunnySymbolsInCode

for reasons that are explained in the page. Just letting you know.

Gavin

···

----- Original Message -----
From: “Gavin Sinclair” gsinclair@soyabean.com.au

~ << >> & ^ |

  1. “<<” most often means that a “here” document follows, e.g.:

    puts <<EOS
    This is a here document.
    EOS

  2. “<<” also creates a new class based on a particular object.
    These object-specific classes are called ‘singleton classes’.
    In the example below, only the Car object referred to by
    “camaro” will have the method “has_flames?”.

    camaro = Car.new
    class << camaro
    def has_flames?
    true
    end
    end

  1. “<<” is also the operator for appending to an array/string in place
    a = [1,2,3]
    a += [4,5] # Creates a new array object and assigns it to a
    a << [4,5] # appends [4,5] directly to the array object a points
    # to

(personally, I use that even more than I do here documents)

. …

And that should be ‘…’ where you have ‘.’

martin

···

Gavin Sinclair gsinclair@soyabean.com.au wrote:

      • / % **
    1. Binary arithmetic operators representing addition (3 + 2),
      subtraction (3 - 2), multiplication (3 * 2), division (3 /
      2), modulus (integer division remainder; 3 % 2 is 1), and
      exponentiation (3 ** 2 is 9). “**” has the highest
      precedence, followed by “*”, “/”, and “%”, and finally “+”
      and “-”. All of these operators are methods.

    2. Unary plus and minus (+3, -2). Unary plus and minus have
      higher precedence than “*”, “%”, and “/”, but lower precedence
      than “**”. These are methods (+@ and -@, respectively).

[–snip—]

You may also want to add the string formatting use of ‘%’ somewhere.

ibraheem@ignoramus:$ ruby -e ‘puts “%s maps to %d” % [“one”,1]’
one maps to 1
ibraheem@ignoramus:$

Kindest regards,

		--ibz.
···

~ << >> & ^ |
[…]

  1. “<<” is also the operator for appending to an array/string in place
    a = [1,2,3]
    a += [4,5] # Creates a new array object and assigns it to a
    a << [4,5] # appends [4,5] directly to the array object a points
    # to

(personally, I use that even more than I do here documents)

Thanks Martin. I’ve rearranged that section as well. It now reads <<EOF

~ << >> & ^ |

Binary (bitwise) operators.  "~" returns the bitwise complement of
the value (~2 is -3); "<<" and ">>" shift the bits of the value
left and right by the specified number of bits (2 << 2 is 8 >> 2).
"&", "^", and "|" are bitwise "and" and exclusive and regular "or"
operators.

<<

1.  Appends an Array or String in place.

        a = [1,2,3]
        a << 4                # a == [1,2,3,4]

2.  A "here" document follows, e.g.:

         puts <<EOS
           This is a here document.
         EOS

3.  "<<" also creates a new class based on a particular object.
    These object-specific classes are called 'singleton classes'.
    In the example below, only the Car object referred to by
    "camaro" will have the method "has_flames?".

         camaro = Car.new
         class << camaro
           def has_flames?
             true
           end
         end

EOF

I’ve also added <<EOF

?c

?c is the ASCII value of 'c'.

         ?c   # -> 99
         ?"   # -> 34

@ @@

@var is an instance variable and @@var is a class variable.

EOF

Gavin

···

From: “Martin DeMello” martindemello@yahoo.com

Gavin Sinclair gsinclair@soyabean.com.au wrote:

Done; thanks.

Gavin

···

----- Original Message -----
From: “Ibraheem Umaru-Mohammed” umarumohammed@btinternet.com

You may also want to add the string formatting use of ‘%’ somewhere.

Done.

···

----- Original Message -----
From: “Tim Sutherland” timsuth@ihug.co.nz

In article 04af01c299e6$e35ebdc0$d44532d2@nosedog, Gavin Sinclair wrote:
[…]

<<

  1. Appends an Array or String in place.

    a = [1,2,3]
    a << 4                # a == [1,2,3,4]
    

[…]

Hi Gavin,

It would be nice if you mentioned that in this case << is just a method
which people can define on their own classes.

Gavin Sinclair wrote:

From: “Tim Sutherland” timsuth@ihug.co.nz

It would be nice if you mentioned that in this case << is just a method
which people can define on their own classes.

Done.

Just for kicks, I cranked out all(*) tokens that can be defined as methods:

== >> & - <=> + << === ~ =~ = * | ** / % ^ -@ < >= <= > +@

Gavin, if there’s a place for it, maybe you could list these, too?

Note that -@ and +@ are the method names for unary - and +.

···

----- Original Message -----


(*) or at least all that are defined in built-in ruby modules, as
found by this snippet:

mods = ; ObjectSpace.each_object(Module) {|m|mods << m}
meths = mods.map {|m| m.instance_methods}.flatten
non_alphanumeric_meths = meths.grep(/\A[^\w]+\z/).uniq
puts non_alphanumeric_meths.join(" ")

Just for kicks, I cranked out all(*) tokens that can be defined as methods:

== >> & - <=> + << === ~ =~ = * | ** / % ^ -@ < >= <= > +@

Gavin, if there’s a place for it, maybe you could list these, too?

Very clever, Joel. However, I think that sort of information is not really
relevant to the question.

I’ve added a comment to question 7.2 with your code and results!

Cheers,
Gavin

···

From: “Joel VanderWerf” vjoel@PATH.Berkeley.EDU