From: 7stud -- Date: 2011-03-26T08:43:48+09:00 Subject: Re: How to get the value of a singleton class? Joey Zhou wrote in post #989179: > Here is a sample code: > > str = "ABC" > class << str > p self > end > > What I get is somthing like "#>". > > If "p str", there's an error message: > > x.rb:3:in `singletonclass': undefined local variable or method `str' for > #> (NameError) > > How can I get the value of str("ABC") within the class << str;...;end > block? > By creating a method that does just that: str = "ABC" class << str def show puts self end end str.show Because str calls the show() method, inside show() self is equal to str. You have to realize that when you write this: > str = "ABC" > > class << str > p self > end > it's is the same as doing this: class MyClass p self end obj = MyClass.new p obj --output:-- MyClass # ...and wondering why 'p self' and 'p obj' don't produce the same results. Inside a class, but outside of any method definitions, self is equal to the class--that's why 'p self' gives you the class name. When you do this: class << str .. ... end you have opened up a class--what's called the 'eigenclass' of str. Therefore, everywhere inside there, but outside any method definitions self is the class, and will never be equal to str. -- Posted via http://www.ruby-forum.com/.