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

I assume you do already know singleton classes (and methods), so here’s
only the explanation of the class << self idiom.

Inside a class definition, ‘self’ refers the the class object (that of
class Class):
irb(main):001:0> class A
irb(main):002:1> puts self
irb(main):003:1> end
A
nil
irb(main):004:0>

So when we do ‘class << self’ we’re grabbing the current class object’s
singleton class to add to it a singleton method which will become a class method:

So
class A
class << self
def doit
puts “BLA”
end
end
end

is mostly equivalent to
class A
def A.doit
puts “BLA”
end
end

See one of Guy’s (ts) posts on this thread for more info.

···

On Mon, Dec 02, 2002 at 02:54:03AM +0900, Shannon Fang wrote:

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.


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

…Deep Hack Mode – that mysterious and frightening state of
consciousness where Mortal Users fear to tread.
– Matt Welsh

def Array.newmethod1
[define]
end

or you can say

class << Array
[define]
end

These two are good. The first one is perfectly clear. The second one is quite
nice.

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.

That, to me, is obfuscated. ‘self’ is generally understood as the current
instance of the class. Therefore, it is only meaningful inside instance
methods. In the “class << self” idiom, there is no instance method. ‘self’
may be defined, but it’s not meaningful in the sense described above.
There’s a yawning gulf between syntax and semantics, and I suggest that it’s
taking advantage of an undocumented feature.

My justification is that I have read a lot of Ruby documentation, and have
become proficient at the language, but the rationale for “class << self” has
never been impressed on me. In particular, the fact that ‘self’ has meaning
immediately inside a class definition has not been impressed on me.

That’s why I wrote in an earier post that one shouldn’t need to be mindful of
Ruby’s metaclass model when performing the perfectly normal OO practice of
defining class (not instance) methods. The means of doing that should be more
intuitive.

Why would you say
class Array
class << self

end
end
when you can say
class Array
class << Array

end
end
?

The latter is much clearer to me. This applies to _why’s (very good) example
as well:
class Win32API
class << Win32API
def def_api

end
end
end

BTW, I’m not trying to be difficult. I hope to read an equally robust reply in
support of “class << self”.

Cheers,
Gavin

···

From: “Martin DeMello” martindemello@yahoo.com

I knew there was a difference, but I really expected something “bigger”.
When I saw it, I thought “it introduces another scope, so what?”. Is
there something obvious I’m not seeing there? Or is the new scope all
there’s to see?

···

On Mon, Dec 02, 2002 at 02:19:46AM +0900, ts wrote:

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

A::a
A::b
pigeon%

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


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

And 1.1.81 is officially BugFree™, so if you receive any bug-reports
on it, you know they are just evil lies.
– Linus Torvalds

mean?)

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

That, to me, is obfuscated. ‘self’ is generally understood as the current
instance of the class. Therefore, it is only meaningful inside instance
methods. In the “class << self” idiom, there is no instance method.
‘self’
may be defined, but it’s not meaningful in the sense described above.
There’s a yawning gulf between syntax and semantics, and I suggest that
it’s
taking advantage of an undocumented feature.

Hmmmmm. This always makes my brain itch, but I’ll make
a stab at it.

I guess I would say that Ruby is OO “even when it isn’t” –
in the sense that a “toplevel” method or constant belongs
to Object.

You may argue that it doesn’t make sense – and maybe you
are right – but I think “self” is always defined in Ruby.
The one-line programs “puts self” and “puts self.class”
will print “main” and “Object” respectively.

Given this paradigm, it does arguably seem natural that in
the middle of a class definition, “self” takes on the value
of the class.

And of course, Class#meth (instance method of Class) means
that there will be a Foo.meth (class method of Foo) for
every class Foo; and a singleton method for the singleton
class of a class is the same as a class method for the
class. Isn’t it? :wink:

Hal

···

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

Hi Gavin,

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.

That, to me, is obfuscated. ‘self’ is generally understood as the current
instance of the class.

Yes!

Therefore, it is only meaningful inside instance methods.

Hang on… let the beauty of Ruby flow through you… (Heh,
sorry - I was considering attempting some corny Star Wars reference,
culminating in, ‘You’ve taken your first step into a larger world…’
… but I’ve out-cornballed myself, and I can’t go through with it :wink:

The beauty here, folding in meta-classes into the mix - and, as I
understand it - is: Class, and the definitions thereof, in Ruby, are
less of a special case than languages such as C++ or Java. ‘self’ is
relevant inside a class definition in Ruby. Think about the possible
implications of the interpreter actually executing statements inside
a class definition when they occur in the source…

class X
@@my_self = self # consider executed right now during the definition of ‘X’
def X.my_self; @@my_self; end
end
nil
X.my_self
X
X.my_self.class
Class
X.my_self.methods.include? “my_self”
true
X.id
22405636
X.my_self.id
22405636

‘self’ during the definition of class X, is an instance of Class.
It’s the particular instance of Class representing X.

. . . Anyway, I’d recommened the section in chapter 19 of Pickaxe,
entitled, “What’s the Meta?” – I just re-read it myself and I’d
forgotten a bit of it…

Uhhhhhh… hope this helps

Regards,

Bill

···

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

Hi –

From: “Martin DeMello” martindemello@yahoo.com

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.

That, to me, is obfuscated. ‘self’ is generally understood as the current
instance of the class. Therefore, it is only meaningful inside instance
methods. In the “class << self” idiom, there is no instance method. ‘self’
may be defined, but it’s not meaningful in the sense described above.
There’s a yawning gulf between syntax and semantics, and I suggest that it’s
taking advantage of an undocumented feature.

(Hmmm… none of this was undocumented last time I checked…)

There’s no necessary connection between self and being inside an
instance method definition. I’m not sure where that idea came from,
but it’s not the case. There’s always a ‘self’.

My justification is that I have read a lot of Ruby documentation, and have
become proficient at the language, but the rationale for “class << self” has
never been impressed on me. In particular, the fact that ‘self’ has meaning
immediately inside a class definition has not been impressed on me.

class << self is really not a special case though; it’s just one use
of the “class << object” idiom, so no separate syntax or design
decision is involved. self is an object, and therefore it can occupy
the ‘object’ slot in the idiom.

As for what happens at the top level of a class definition: a class
does have state, outside of its instance method definitions, and it is
an object and has a singleton class (as well as a real class). So
there has to be some way to get at those things. Actually… it’s
interesting to play around with other ways. For example:

c = Class.new(Array)
c.instance_eval {
def class_talk
puts “I’m a class: #{self}”
end
class_eval {
def speak
puts “I’m an instance of #{self.class}”
end
}
}

c.class_talk
c.new.speak

I find this useful in getting a slightly different view of what’s
going on with ‘self’ and class definitions. (In fact, I’ve heard a
case made that the ‘class’ keyword should be done away with, in favor
of the use of explicit Class instance constructors, but I’m not sure
I’m aligned with that view :slight_smile:

That’s why I wrote in an earier post that one shouldn’t need to be
mindful of Ruby’s metaclass model when performing the perfectly
normal OO practice of defining class (not instance) methods. The
means of doing that should be more intuitive.

I’ve grown very skeptical of the notion of intuitiveness in computer
programming languages :slight_smile: But anyway, I think that the most common
syntax for class method definition (def MyClass.meth) allows for a
nice clear syntax which also happens to take the form of just adding a
method to an object’s singleton class (but you don’t have to worry
about that level of it when writing the method).

Why would you say
class Array
class << self

end
end
when you can say
class Array
class << Array

end
end
?

Actually in that case I would just say:

class << Array

end

and dispense with the surrounding class/end pair (unless there’s
something else going on there). If you do need the nesting, I
personally find class << self to be slightly clearer, but it might
depend on what else was interposed in the nesting. It’s also slightly
more maintainable, in the sense that if you change a class name, the
‘self’ reference updates itself automatically.

David

···

On Mon, 2 Dec 2002, Gavin Sinclair wrote:


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

That, to me, is obfuscated. ‘self’ is generally understood as the current
instance of the class.

Yes.

Therefore, it is only meaningful inside instance methods.

Well, not really. Self is available anytime there is a “current
instance” active … which is all the time in Ruby.

At the top level, self refers to the “main” object …

traken$ irb
irb(main):001:0> self
main

Inside a class definition, the current instance is the class itself!
That is why attr_reader (and its friends) work. Bare code (i.e. anyting
not inside a method definition) is live code that is executed. What is
the object that handles method calls inside a class? It is the class
object. So the current instance inside a class definition is the
instance of the Class object being defined, in other words … self.

This is what allows things like “attr_reader” to work. attr_reader is a
method defined in the class object. For example the following code …

class A
attr_reader :prop
end

is equivalent to …

class A
self.attr_reader :prop
end

(except that attr_reader is private and so won’t work with an explicit
target. You can fix this with: class Module; public :attr_reader; end)

If self didn’t refer to the class instance, the call to the attr_reader
method wouldn’t work.

There’s a yawning gulf between syntax and semantics, and I suggest that it’s
taking advantage of an undocumented feature.

Actually, you can argue that there is the syntax and semantics are
tightly coupled. Knowing what “class << obj” means and knowing that
inside a class, self is the current class instance, directly leads to
the meaning of “class << self”.

···

On Sun, 2002-12-01 at 20:44, Gavin Sinclair wrote:


– Jim Weirich jweirich@one.net http://w3.one.net/~jweirich

“Beware of bugs in the above code; I have only proved it correct,
not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)

Therefore, [‘self’] is only meaningful inside instance methods.

Hang on… let the beauty of Ruby flow through you… [snip]

The beauty here, folding in meta-classes into the mix - and, as I
understand it - is: Class, and the definitions thereof, in Ruby, are
less of a special case than languages such as C++ or Java. ‘self’ is
relevant inside a class definition in Ruby. Think about the possible
implications of the interpreter actually executing statements inside
a class definition when they occur in the source…

I’m well aware of that, and have seen it used to great effect: the
auto-generation of a whole lot of methods. Heck, even attr_* does this, and
that’s what I love about Ruby.

I very much like the meta-class stuff. It’s just that - like it or not -
“class << self” is probably a lot more confusing for new people than anything
else about Ruby.

. . . Anyway, I’d recommened the section in chapter 19 of Pickaxe,
entitled, “What’s the Meta?” – I just re-read it myself and I’d
forgotten a bit of it…

Will do. Thanks for the tip.

Cheers,
Gavin

···

----- Original Message -----
From: “Bill Kelly” billk@cts.com

I knew there was a difference, but I really expected something "bigger".
When I saw it, I thought "it introduces another scope, so what?".

Strange that you see a scope, where I see a class :slight_smile:

Probably I'm wrong.

Guy Decoux

I knew there was a difference, but I really expected something “bigger”.
When I saw it, I thought “it introduces another scope, so what?”.

Strange that you see a scope, where I see a class :slight_smile:

Probably I’m wrong.

U joking? Who’s the Ruby hacker extraordinaire (and Frenchman too :slight_smile:
here (*)? If anything I must be wrong, but I’m not sure why.

Do you mean that in

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

A.a is defined “directly” implementation-wise and A.b via an anonymous
singleton class? If so, when doing A.a Ruby would find that method
directly in the class method table of class A, but for A.b it’d have to
look for that method in the singleton class.

Do things happen this way, or is the “class” vs “scope” thing just a
wording issue?

(*) je ne suis qu’à moitié français! :wink:

Maurice Julien Fernández Pradier
···

On Mon, Dec 02, 2002 at 09:40:27PM +0900, ts wrote:


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

snafu = Situation Normal All F%$*ed up

A.a is defined "directly" implementation-wise and A.b via an anonymous
singleton class? If so, when doing A.a Ruby would find that method
directly in the class method table of class A, but for A.b it'd have to
look for that method in the singleton class.

No, no. A::a and A::b are in the same singleton class.

Guy Decoux