How to find self class name inside self difinition?


#1

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 ?


#2

Thani A. wrote:

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


#3

Thani A.:

module Aa
end

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

(This is correct; the object ‘Aa::Name’ is of class ‘Class’.)

But i want my class name as ‘Aa::Name’ instead of ‘Class’

You want the Module#name method:

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

Aa::Name.class_name # => ‘Aa::Name’

– Shot


#4

module Aa
end

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


#5

Thanks


#6

Thani A. wrote:

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


#7

2008/11/10 Stephen P. removed_email_address@domain.invalid:

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