[FAQ] What do some of Ruby's symbols mean?

This could do with some community input before going to the FAQ. The format
will be different but I just wanted to bang out some content. I haven’t even
checked if there is a question like this.

Can anyone think of a question title that does’t create confusion with :name
symbols?

···

Q: What do some of Ruby’s symbols mean?

A:

This question is about non-aplhanumeric characters in Ruby code, not about
symbols like :name. For those, see [appropriate link]. Actual explanations
of the concepts behind them is beyond the scope of this answer.

<= < != == > >>
Relational operators, as per most other computer languages. Are often
redefined for use with various classes.

      • / %
        Common arithmetic operators. Some are defined also for String, Array
        and others.

===
Case comparison operator. Used to select branches in case statements.

<
Class inheritance, as in
class Car < Vehicle
end

<<
Funny class inheritance; see [appropriate link] for a rationale. Also
commonly used as a method for appending (e.g. Array and String).

… …
Range definers, as in 0…10 and “a”…“z”

:
Symbol definer, as in :name, where :name.to_s == “name”. See [a/l].
See next item also.

?:
Ternary decision operator, as in C. For example:
iq = (position == MANAGER) ? LOW : HIGH

{} =>
Hash definition, as in
numstr = { 1 => “one”, 2 => “two”, … }

[]
Array definition, as in
ndays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]

%w[]
String-Array converter, as in
dayabbrev = %w[Sun Mon Tue Wed Thu Fri Sat]
dayabbrev == [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”]

//
Regular expression definition, as in
date_re = /(\d\d\d\d)-(\d\d)-(\d\d)/
y, m, d = date_re.match(“2002-12-01”)[1…3]

?!
Suffixes for methods (optional, of course). In general:
method! changes the object (e.g. String.gsub!)
method? returns boolean (e.g. Array.empty?)

Hello,

···

On Sun, Dec 01, 2002, Gavin Sinclair wrote:

?:
Ternary decision operator, as in C. For example:
iq = (position == MANAGER) ? LOW : HIGH

being a manager (as a part time job ;)), i’d rather see a more explicit
example for this ternary operator such as

temperature = ( weather == SNOW) ? LOW : HIGH

I’m not sure someone will not try to guess the behaviour of the ternary
operator from your example, but i might be wrong…

Cheers,

Pierre Baillet
It is bad when one thing becomes two. One should not look for anything else in
the Way of the Samurai. It is the same for anything that is called a Way. If
one understands things in this manner, he should be able to hear about all ways
and be more and more in accord with his own.
Ghost Dog - The Way of the Samouraï

<<
   Funny class inheritance;

This is not an inheritance.

When you write

    class << obj
    end

you access the singleton class which is associated with `obj', id *don't*
exist an inheritance relation between this class and `obj' (except for the
very special case `class << Object' but this is because Object is the root
of the hierarchy)

Guy Decoux

Hi –

···

On Sun, 1 Dec 2002, Gavin Sinclair wrote:

<<
Funny class inheritance; see [appropriate link] for a rationale. Also
commonly used as a method for appending (e.g. Array and String).

Can you phrase this in such a way that it doesn’t sound like something
terribly weird or arcane? It would really be too bad to taint this
powerful and perfectly idiomatic technique with that reputation.

David


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

This could do with some community input before going to the FAQ.
The format will be different but I just wanted to bang out some
content. I haven’t even checked if there is a question like this.

Can anyone think of a question title that does’t create confusion
with :name symbols?

[FAQ] What do you mean, <=!@/$!?

Half tongue in cheek.

Q: What do some of Ruby’s symbols mean?

A: This question is about non-aplhanumeric characters in Ruby
code, not about symbols like :name. For those, see [appropriate
link]. Actual explanations of the concepts behind them is beyond
the scope of this answer.

[Note: As I am defining these, I am going from most frequent to
least frequent use for the various default definitions.]

<=>, <=, <, >=, >, ==, !=
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 must
return a value of -1, 0, or +1). All other relational
operators, if defined manually, must return a boolean value
(either FalseClass or TrueClass). 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. Binomial 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 opens an object for modification to make a
    singleton-object (one which is not quite like any other
    object of its class). 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.
···

On Sun, 1 Dec 2002 23:07:25 +0900, Gavin Sinclair wrote:

===
Case comparison operator. Used to select branches in case
statements.

., …
Range defnitions. “…” ranges are end-inclusive; “…” ranges
are end-exclusive. See [Range].

:, ?:, ::
1. Symbol mark. This marks the name as a Symbol, such that
: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:

      (boolean-test) ? (do-if-true) : (do-if-false)

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.


1. References an element of a collection. This is a method
call, defined as “”. Defining this method also gets
=” for free.
2. Array definition, as in:

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

{}, =>
Hash definition, most often used with “=>”. Can be used in one
of two ways. The example 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”.

=~, !~, //, %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.

%x{}
A command string. This behaves the same as backtick (``) command
execution.

-austin
– Austin Ziegler, austin@halostatue.ca on 2002.12.01 at 10.18.42

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

<<
Funny class inheritance; see [appropriate link] for a rationale.

What’s wrong with “Used for adding methods to an individual object”?
That’s a lot less scary.

?!
Suffixes for methods (optional, of course). In general:

Not sure “optional” is the best word here. If the ! suffix really was
optional, then s.gsub would do the same as s.gsub!

···


Life would be so much easier if we could just look at the source code.
– Dave Olson

Hi David

Can you phrase this in such a way that it doesn’t sound like something
terribly weird or arcane? It would really be too bad to taint this
powerful and perfectly idiomatic technique with that reputation.

I fully respect the effort all the community members and developers are
developing the language… But at my level, I can’t understand the
beauty of using a sigleton class associated with an object. I can only
manage to understand class method/instance method, and some basics of
mixins, which I think is exactly same as java interfaces.

Could you please give me an example to illustrate why we need class <<
obj? May be it is also a good thing if we can collect some explanations
to such thing, I think it will be a good text book for understanding OOP.

Shannon

···

On Sun, 1 Dec 2002 23:17:15 +0900 dblack@candle.superlink.net wrote:

Austin Ziegler austin@halostatue.ca writes:

<=>, <=, <, >=, >, ==, !=
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 must
return a value of -1, 0, or +1).

Actually, it’s looser than that: the spaceship can return less than
zero, zero, or greater than zero.

+, -, *, /, %, **
1. Binomial arithmetic operators representing addition (3 + 2),

Simple typo for ‘binary’.

2.  "<<" also opens an object for modification to make a
    singleton-object (one which is not quite like any other
    object of its class). In the example below, only the Car
    object referred to by "camaro" will have the method
    "has_flames?".

Possibly “Creates a new class based on a particular object. These
object-specific classes are called ‘singletons’ (or singleton
classes). In the example…”

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

If a singleton class for a object already exists, << simply modifies
it, rather than creating a new one.

A common idiom is “class <<self;methods…;end”, found inside class
definitions. As ‘self’ inside a class definition references the class
object, this somewhat strange construct ends up adding methods at the
class (as opposed to instance) level.

How about “an optional but useful naming convention for methods”?

martin

···

Simon Cozens simon@simon-cozens.org wrote:

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

?!
Suffixes for methods (optional, of course). In general:

Not sure “optional” is the best word here. If the ! suffix really was
optional, then s.gsub would do the same as s.gsub!


1. References an element of a collection. This is a method
call, defined as “”. Defining this method also gets
=” for free.

Not in 1.6.5, at least. What about other versions?

Gavin

···

From: “Austin Ziegler” austin@halostatue.ca

I fully respect the effort all the community members and developers are
developing the language... But at my level, I can't understand the
beauty of using a sigleton class associated with an object. I can only
manage to understand class method/instance method, and some basics of
mixins, which I think is exactly same as java interfaces.

If instance methods are stored in the class, where do you think that the
class methods are stored ?

Guy Decoux

Hi,

···

On Sun, 1 Dec 2002 23:35:30 +0900 ts decoux@moulon.inra.fr wrote:

If instance methods are stored in the class, where do you think that the
class methods are stored ?

I’m sorry I can’t understand the purpose of your question. Is it related
to understanding class << object? The level I’m interested in is for
application developers, why they need to use <<, does it make their life
easier, or…? I did not consider to make the language developer’s life
easier… (sorry for being selfish :-p).

Shannon

I'm sorry I can't understand the purpose of your question. Is it related
to understanding class << object? The level I'm interested in is for
application developers, why they need to use <<, does it make their life
easier, or...? I did not consider to make the language developer's life
easier.. (sorry for being selfish :-p).

See [ruby-talk:56900]

Guy Decoux

Hi,

If instance methods are stored in the class, where do you think that the
class methods are stored ?

I’m sorry I can’t understand the purpose of your question. Is it related
to understanding class << object? The level I’m interested in is for
application developers, why they need to use <<, does it make their life
easier, or…? I did not consider to make the language developer’s life
easier… (sorry for being selfish :-p).

Shannon

You know what a class method is, right?

class Example
def Example.foo
19
end
end

Example.foo # → 19

The same is achieved with

class Example
class << self
def example
19
end
end
end

I don’t know why and I don’t like it. I’m happy enough with singleton objects
(but what’s wrong with “def obj.meth”?):

class << object
def to_s
“something unexpected”
end
end

But I don’t see why I should juggle Ruby meta-class models in my head just to
define class methods.

One advantage of the apparently beautiful “class << self” is that you can
define several class methods at once without explicitly typing the class name,
but I don’t see what’s gained here. To me it’s obfuscated, and even when
understood - or merely acknowledged - I think the notation is unintuitive.

Hopefully I’m missing something and am about to have my fourth Ruby epiphany :slight_smile:

Gavin

···

From: “Shannon Fang” xrfang@hotmail.com

On Sun, 1 Dec 2002 23:35:30 +0900 > ts decoux@moulon.inra.fr wrote:

The class << self syntax isn’t terribly difficult to understand once you
actually find a use for it. I usually use it a couple times in many of
the applications I write.

I find it useful for adding methods which I can use in my class
descriptions. For example, I worked on an application which
communicated quite a bit with the Windows API. I wrote a wrapper class
using class << self.

require 'Win32API'

class Win32Wrapper
  # Abstract away the Win32API wrapper
  class << self
    def def_api( methName, winName, imp, exp )
      class_eval %{
        def #{methName}( *a )
          Win32API.
            new( '#{self.name.upcase}', '#{winName}', #{imp.inspect}, #{exp.inspect} ).
            call( *a )
        end
      }
    end
  end
end

The code is a bit thick, so you might notice that I’m defining a
`def_api’ method inside of the class << self. Now I call that method in
my class definitions:

# User32 DLL
class User32 < Win32Wrapper
  def_api :desktop, :GetDesktopWindow, [], 'L'
  def_api :activeWindow, :GetActiveWindow, [], 'L'
end

Using the `def_api’ method in my class definitions makes them look a
lot cleaner. Just using a normal method definition would bloat my
classes to look like this:

# User32 DLL
class User32 < Win32Wrapper
  def desktop( *a )
    Win32API.
      new( 'USER32', 'GetDesktopWindow', [], 'L' ).
      call( *a )
  end
  def activeWindow( *a )
    Win32API.
      new( 'USER32', 'GetActiveWindow', [], 'L' ).
      call( *a )
  end
end

I personally prefer class << self in many situations, because I don’t
have to litter my code with the class name either.

_why

···

Shannon Fang (xrfang@hotmail.com) wrote:

I’m sorry I can’t understand the purpose of your question. Is it related
to understanding class << object? The level I’m interested in is for
application developers, why they need to use <<, does it make their life
easier, or…? I did not consider to make the language developer’s life
easier… (sorry for being selfish :-p).

Hi –

From: “Shannon Fang” xrfang@hotmail.com

Hi,

If instance methods are stored in the class, where do you think that the
class methods are stored ?

I’m sorry I can’t understand the purpose of your question. Is it related
to understanding class << object? The level I’m interested in is for
application developers, why they need to use <<, does it make their life
easier, or…? I did not consider to make the language developer’s life
easier… (sorry for being selfish :-p).

Shannon

You know what a class method is, right?

class Example
def Example.foo
19
end
end

Example.foo # → 19

The same is achieved with

class Example
class << self
def example
19
end
end
end

I don’t know why and I don’t like it. I’m happy enough with
singleton objects (but what’s wrong with “def obj.meth”?):

Nothing, but it can get tedious:

class A
def self.thing
@thing
end
def self.thing=(x)
@thing = x
end
end

as opposed to:

class A
class << self
attr_accessor :thing
end
end

(You could of course just add the attribute to the object’s real
class:

class Class
attr_accessor :thing
end

but then every Class object (String, Array, etc.) would have this
attribute.)

The class << obj idiom is based on two fundamental things about Ruby:

  1. you can open/reopen any class:

class String …

class MyClass …

  1. every object (almost) has a singleton class

So class << obj is just a way of accomplishing #1 with regard to #2.
It thus provides a way to treat singleton classes very much like
generic (if that’s the word) classes, which makes for what I think is
a nice consistency and seamlessness. But there’s no imperative that
you use this idiom, if you don’t like it and can write around it.

David

···

On Sun, 1 Dec 2002, Gavin Sinclair wrote:

On Sun, 1 Dec 2002 23:35:30 +0900 > > ts decoux@moulon.inra.fr wrote:


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

It seems consistent to me. If you wanted to define several methods for
class Array, you’d write

class Array
[define methods here]
end

and all instances of Array can now use your methods

similarly, if you want to define several methods for an object’s singleton
class, you write

class << object
[define methods here]
end

and all instances of object’s singleton class (i.e., just object) can
now access the methods.

As for class methods - well, a class is just an instance of class Class.
Therefore, it has methods which are instance methods of Class. You can
add in methods by saying

class Class
[define methods here]
end

and all classes will now have the new class methods. If you want class
methods for a single class, you are actually tacking on methods to an
object, in much the same way as “def a.newmethod” would. So you can use
that syntax:

def Array.newmethod1
[define]
end

or you can say

class << Array
[define]
end

or, if you are already in class Array and defining instance methods,
you can highilght the fact that you’re working in the same conceptual
space by taking advantage of Ruby’s setting ‘self’ to ‘Array’ when you say
‘class Array’, and writing

class Array
def instancemethod
[define]
end

class << self
def classmethod
[define]
end
end
end

There’s no arcane magic going on here - self is an object of class
Class, and in this case it has the value Array.

Try the following:

class Array
p self
p self.class
p self.id
end

class << Array
p self
p self.class
p self.id
end

class Array
class << self
p self
p self.class
p self.id
end
end

a = Array.new
class << a
p self
p self.class
p self.id
end

and, to prove that singleton classes are being created, even though they
all say Array,

b = Array.new
class << b
p self
p self.id
end

p Array.id

martin

···

Gavin Sinclair gsinclair@soyabean.com.au wrote:

But I don’t see why I should juggle Ruby meta-class models in my head
just to define class methods.

One advantage of the apparently beautiful “class << self” is that you
can define several class methods at once without explicitly typing the
class name, but I don’t see what’s gained here. To me it’s
obfuscated, and even when understood - or merely acknowledged - I
think the notation is unintuitive.

Hopefully I’m missing something and am about to have my fourth Ruby
epiphany :slight_smile:

But I don’t see why I should juggle Ruby meta-class models in my head just
to
define class methods.

One advantage of the apparently beautiful “class << self” is that you can
define several class methods at once without explicitly typing the class
name,
but I don’t see what’s gained here. To me it’s obfuscated, and even when
understood - or merely acknowledged - I think the notation is unintuitive.

Hopefully I’m missing something and am about to have my fourth Ruby
epiphany :slight_smile:

Perhaps it has something to do with modules. You
can define a class method without knowing the
name of the class. (Hmm. True? I did some research
once but it didn’t stick to my Teflon brain.)

But then, I find that “def self.meth” seems to
work fine…

In any case, didn’t Matz once say that the
“class << self” notation was to be discouraged
in the future? Or am I mistaken?

Hal

···

----- Original Message -----
From: “Gavin Sinclair” gsinclair@soyabean.com.au
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Sunday, December 01, 2002 8:58 AM
Subject: class << self (was Re: [FAQ] What do some of Ruby’s symbols mean?)

Hi

I appreciate the benefit. But some problem not clear:

  1. what is the symbol %{ mean? I knew there are %w %Q %q etc, but %{ ??
  2. My inital question about << is class << anObj. Don’t know when it
    became class << self?? Is << only used with self?

After I understand why class << self, and re-read the pickaxe, I’ll be
able to under stand your code better.

Thanks a lot
Shannon

···

On Mon, 2 Dec 2002 02:20:19 +0900 why the lucky stiff ruby-talk@whytheluckystiff.net wrote:

I find it useful for adding methods which I can use in my class
descriptions. For example, I worked on an application which
communicated quite a bit with the Windows API. I wrote a wrapper class
using class << self.

require 'Win32API'

class Win32Wrapper
  # Abstract away the Win32API wrapper
  class << self
    def def_api( methName, winName, imp, exp )
      class_eval %{
        def #{methName}( *a )
          Win32API.
            new( '#{self.name.upcase}', '#{winName}', #{imp.inspect}, #{exp.inspect} ).
            call( *a )
        end
      }
    end
  end
end

But then, I find that "def self.meth" seems to
work fine...

it work fine, but sometimes it exist a difference

pigeon% cat b.rb
#!/usr/bin/ruby
class A
   B = 12
   def self.a
      puts "class method A::a : #{B}"
   end

   class << self
      B = 24
      def b
         puts "class method A::b : #{B}"
      end
   end
end

pigeon%

pigeon% b.rb
class method A::a : 12
class method A::b : 24
pigeon%

Guy Decoux

···

A::a
A::b