how to find self class name inside self difinition ?

T

Thani Ararsu

module Aa
end

class Aa::Name
def self.class_name
self.class.name
end
end
puts Aa::Name.class_name # 'Class'

# But i want my class name as 'Aa::Name' instead of 'Class'


any idea ?
 
S

Stefan Rusterholz

Thani said:
module Aa
end

class Aa::Name
def self.class_name
self.class.name
end
end
puts Aa::Name.class_name # 'Class'

# But i want my class name as 'Aa::Name' instead of 'Class'


any idea ?

Just drop the .class part.
class Aa::Name
def self.class_name; self.name; end # self is redundant so:
def self.class_name; name; end # now for this we got a nice little
construct that goes:
class << self
alias class_name name
end
end

Regards
Stefan
 
X

xue19840909

module Aa
end

class Aa::Name
def class_name
self.class.name
end
end
puts Aa::Name.new().class_name
 
S

Stephen Pearson

Thani said:
module Aa
end

class Aa::Name
def self.class_name
self.class.name
end
end
puts Aa::Name.class_name # 'Class'

# But i want my class name as 'Aa::Name' instead of 'Class'


any idea ?

module Aa
end

class Aa::Name
def self.class_name
name
end
end
puts Aa::Name.class_name

Or dispense with the class method entirely:

puts Aa::Name.name
 
R

Robert Klemme

2008/11/10 Stephen Pearson said:
module Aa
end

class Aa::Name
def self.class_name
name
end
end
puts Aa::Name.class_name

Or dispense with the class method entirely:

That would be my advice as well. Note also that Module#to_s is an
alias for Module#name so you can even print the class object directly
(if it is for output purposes).
puts Aa::Name.name

Ruby version 1.8.7
irb(main):001:0> module Aa
irb(main):002:1> class Name
irb(main):003:2> puts name, self.name, self
irb(main):004:2> end
irb(main):005:1> end
Aa::Name
Aa::Name
Aa::Name
=> nil
irb(main):006:0>


Kind regards

robert
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top