Hi,
I'd like to use the name of my class in a class method. I've tried
self.class.to_s but that outputs "Class". I've attached my code below
Thanks,
Peter
class Thing
def self.my_name
# I don't want to reference instance method my_name
self.class.to_s
end
def self.my_name2
self.new.my_name
end
def my_name
self.class.to_s
end
end
# I want these three lines to output "Thing"
puts Thing.my_name #outputs "Class"
puts Thing.my_name2 #outputs "Thing"
puts Thing.new.my_name #outputs "Thing"
Just use self.to_s or name in a class method, e.g.
class Thing
def self.my_name
self.to_s
end
def self.my_name2
name
end
end
t = Thing.new
puts Thing.name
puts Thing.my_name
puts Thing.my_name2
__END__
Thing
Thing
Thing
Regards,
Sean
···
On 11/7/05, petermichaux@yahoo.com <petermichaux@yahoo.com> wrote:
I'd like to use the name of my class in a class method. I've tried
self.class.to_s but that outputs "Class". I've attached my code below
Hi,
I'd like to use the name of my class in a class method. I've tried
self.class.to_s but that outputs "Class". I've attached my code below
Thanks,
Peter
class Thing
def self.my_name
# I don't want to reference instance method my_name
self.class.to_s
end
def self.my_name2
self.new.my_name
end
def my_name
self.class.to_s
end
end
# I want these three lines to output "Thing"
puts Thing.my_name #outputs "Class"
puts Thing.my_name2 #outputs "Thing"
puts Thing.new.my_name #outputs "Thing"
That is because the class of a class is class.
$ irb --simple-prompt
12.class
=> Fixnum
12.class.class
=> Class
12.class.class.class
=> Class
class A; p self; end
A
=> nil
class A; p self.class; end
Class
=> nil
class A; def self.a; self; end; end; A.a
=> A
cheers,
Brian
···
On 07/11/05, petermichaux@yahoo.com <petermichaux@yahoo.com> wrote:
--
http://ruby.brian-schroeder.de/
Stringed instrument chords: http://chordlist.brian-schroeder.de/