class << self

P

Patrick Doyle

Sorry if this is a FAQ, but I was just looking at some Ruby code and
came across the following construct:

class << self
def blahblahblah
...
end
end

I wondered what that did, went looking, and came across this email
thread from 2002:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/57244, in
reading that, I came across this (slightly modified) code:

class A
B = 12
def self.a
puts "class method A::a : #{B}"
end

def A.b
puts "class method A::b : #{B}"
end

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

end
A.a
A.b
A.c
puts "A::B : #{A::B}"

Could somebody enlighten me as to what is going on here? I didn't
completely follow all of the ins & outs of the thread, nor why

def self.a

is better/different than

def A.a

is better different than

class << self
def a

Can anybody comment or point me in the direction of some enlightenment?

--wpd
 
J

Jeremy McAnally

None of them are really better; they all do the same thing. :)

The first and second approaches (to me) make it easier to discern, at
a glance, what's a class method and what's an instance method. On the
other hand, the last one (class << self) keeps you from re-typing the
class name/self over and over again.

--Jeremy

Sorry if this is a FAQ, but I was just looking at some Ruby code and
came across the following construct:

class << self
def blahblahblah
...
end
end

I wondered what that did, went looking, and came across this email
thread from 2002:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/57244, in
reading that, I came across this (slightly modified) code:

class A
B = 12
def self.a
puts "class method A::a : #{B}"
end

def A.b
puts "class method A::b : #{B}"
end

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

end
A.a
A.b
A.c
puts "A::B : #{A::B}"

Could somebody enlighten me as to what is going on here? I didn't
completely follow all of the ins & outs of the thread, nor why

def self.a

is better/different than

def A.a

is better different than

class << self
def a

Can anybody comment or point me in the direction of some enlightenment?

--wpd



--
http://jeremymcanally.com/
http://entp.com/
http://omgbloglol.com

My books:
http://manning.com/mcanally/
http://humblelittlerubybook.com/ (FREE!)
 
P

Patrick Doyle

[Note: parts of this message were removed to make it a legal post.]

Well, there is one difference -- the last one returns a different value for
B. I'm not sure what that buys you, but it's the thing that dumbfounds me
the most about this issue.

--wpd
Well, there is one difference -- the last one returns a different value for
B. I'm not sure what that buys you, but it's the thing that dumbfounds me
the most about this issue.

--wpd
 
S

Suraj Kurapati

Patrick said:
Well, there is one difference -- the last one returns a different value
for B.

Remember that (1) classes are also objects in Ruby and (2) every object
in Ruby has its own singleton class (also known as "meta class" and
"eigen class"). An object's singleton class is like a human's
personality -- each personality is unique to the particular human.

When you write:

def my_object.my_method
...
end

you are using a shortcut for:

class << my_object
# we are inside my_object's singleton class! :)


def my_method
...
end
end

Thus, you are adding a my_method to the personality of my_object.
I'm not sure what that buys you, but it's the thing that dumbfounds
me the most about this issue.

It buys a lot. Imagine you are writing a super hero simulation game
where objects are randomly given super powers. How would you do this?

In Java, the typical approach is to make a class heirarchy:

class Human {}
class Hero extends Human {}
class SuperHero extends Hero {}

Human h = rand(2) == 1 ? new SuperHero() : new Human();

and randomly instantiate the particular SuperHero class.

In Ruby, we can do something better and give super powers directly to a
particular object:

class Human; end

h = Human.new

if rand(2) == 1
def fly!
puts "you soar like an eagle!"
end

def hide!
puts "you became invisible!"
end
end

Understand now?
 
S

Suraj Kurapati

Suraj said:
In Ruby, we can do something better and give super powers directly to a
particular object:

class Human; end

h = Human.new

if rand(2) == 1

class << h
def fly!
puts "you soar like an eagle!"
end

def hide!
puts "you became invisible!"
end end

end

Understand now?

Sorry, I was in a hurry. :)
 
S

Stephen Celis

Hi,

Well, there is one difference -- the last one returns a different value for
B. I'm not sure what that buys you, but it's the thing that dumbfounds me
the most about this issue.

I believe this is an issue of scope, A.c is picking up #<Class:A>::B,
whereas the others are picking up A::B.

Stephen
 
R

ragav

Well, there is one difference -- the last one returns a different value for
B. I'm not sure what that buys you, but it's the thing that dumbfounds me
the most about this issue.

Constant lookup works differently than other kinds of name resolution
in ruby. It walks up the *Lexical Scope* first, ,then the inheritance
chain and finally the top object.

Sprinkle 'Module.nesting' and you'll know the current lexical scope

class A
B =12
def self.a
p Module.nesting #=> [A]
puts "class method A::a : #{B}"
end

class << self #=><Class:A> , creates new lexical scope
B = 24
def c
p Module.nesting #=> [#<Class:A>, A]
puts "class method A::c : #{B}"
end
end

end
A.a
A.c
puts "A::B : #{A::B}"

Not one of the more intuitive pieces in ruby. ;-)

--Cheers
--Ragav
 
W

_why

I believe this is an issue of scope, A.c is picking up #<Class:A>::B,
whereas the others are picking up A::B.

What it buys you is a namespace that cannot be addressed from the
top-level. If you want to create temporary classes that don't
pollute the top-level but can address each other, you can create
them in the singleton class of an object.

A::B can be addressed from anywhere, whereas #<Class::A>::B
cannot (not by that name.)

_why
 
R

Randy Kramer

A::B can be addressed from anywhere, whereas #<Class::A>::B
cannot (not by that name.)

What is the syntax #<Class::A>? (I couldn't (readily, at least) find it
in the index of Pickaxe2, nor is Google helping.)

Randy Kramer
 
R

Ragav Satish

Randy said:
What is the syntax #<Class::A>? (I couldn't (readily, at least) find it
in the index of Pickaxe2, nor is Google helping.)

Randy Kramer

It's just a name for the eigenclass of A

class A
p class << self ; self;end #=> #<Class:A>
end
 
R

Randy Kramer

It's just a name for the eigenclass of A
=20
class A
=C2=A0 p class << self ; self;end =C2=A0#=3D> #<Class:A>
end

Thanks!

Randy Kramer
=2D-=20
I didn't have time to write a short letter, so I created a video=20
instead.--with apologies to Cicero, et.al.
 
P

Patrick Doyle

[Note: parts of this message were removed to make it a legal post.]

Returning to this topic after a brief hiatus being distracted by other
concerns...

Would it be fair to say that 99% of the time there is no difference between
the definitions of A#a, A#b, and A#c?

class A
def self.a
puts "self.a"
end

def A.b
puts "A.b"
end

class << self
def c
puts "A.c"
end
end
end

It seems that the construct:

class << self
def x
end

def y
end

def z
end
end

might be used primarily as a typing shortcut and that 99% of the time that's
all it is.

Would it be fair to say that 100% of the time there is absolutely no
difference between A#a and A#b?

Is it fair to say that the 1% of the time that there's a difference between
A#a and A#c is for constant lookup?

FWIW, I do see a difference between

class A
class << self
def blah
end
end
end

and

something = A.new()
class << something
def something_very_specific_to_this_something()
end
end

and that's a nifty trick. Someday I might even find myself coding something
that just cries out for that trick. Thanks Suraj for showing that to me.

--wpd
 
Y

Yossef Mendelssohn

Would it be fair to say that 99% of the time there is no difference betwe= en
the definitions of A#a, A#b, and A#c?

class A
=A0 def self.a
=A0 =A0 puts "self.a"
=A0 end

=A0 def A.b
=A0 =A0 puts "A.b"
=A0 =A0end

=A0 class << self
=A0 =A0 def c
=A0 =A0 =A0 puts "A.c"
=A0 =A0 end
=A0 end
end

It seems that the construct:

class << self
=A0 def x
=A0 end

=A0 def y
=A0 end

=A0 def z
=A0 end
end

might be used primarily as a typing shortcut and that 99% of the time tha= t's
all it is.

Personally, I use class << self for several reasons:

- It reduces repetition
- I believe it's clear enough
- It makes searching for a method definition in your entire codebase
simpler
- It allows aliasing class methods
- It allows access control (public/private) of class methods

With that in mind, I see def self.meth as a shortcut for class << self
when all you're doing is defining a single method. If anything more is
to be done, it's cleaner overall to enter the eigenclass.

And I use self instead of the literal class name again to reduce
repetition. If you have

class A
def A.a
'got to .a'
end
end

and you decide to change the class name from A to something else,
you're still defining A.a, which is now highly likely to be an error.
If you were using self.a or class << self, the method would still be
defined on whatever the class is now called.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Code sharing 2
Class eval does not work with self 3
class << self 1
Class Variables in EigenClass 10
Class initialization 6
self 16
self in irb versus script 3
special cased? 8

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top