From: Eye Matz Date: 2006-10-03T23:51:47+09:00 Subject: Re: Newbie: Question => How to do this with Classes ? Jean Helou wrote: > now for your example : > class Important > def singleton_class > #get the singleton class for this instance > #A good explanation for the singleton class is available in the > pickaxe book > #if i remember correctly it's in the duck typing section with a > diagram > #which makes it all clear. > class << self; self; end > end > > #define the class method which will be available as a dsl element. > #this is only "syntactic sugar" for your dsl to make it nicer > def self.set_this_value_method(value) > define_attr_method :this_value_method, value > end > > #Then defines a new method called "name" in the singleton class of > the instance. > #note that here the instance is a class thus it adds a class method > def self.define_attr_method(name, value) > singleton_class.class_eval do > define_method(name) do > value > end > end > > end > > > class SemiImportant < Important > set_this_value_method :something_or_anything > end > > now you can call SemiImportant.this_value_method and it will return > :something_or_anything > > jean Hi Jean, Thanks you VERY much for making that example clearer ! One minor error in it, though > def singleton_class > class << self; self; end > end should be def self.singleton_class class << self; self; end end And Yes, I do understand the concept of Singleton classes, just NOT very well in Ruby or in Ruby syntax. My problem is really more to do with the grammatical logic, ie: when should I use this or that, or how should I write this or that to get this or that result. I haven't found a clear and concise account of that, and therefore I am writing stuff like this [ Name are Matz I ] in Ruby, and things don't work so well then. Thank you for your help! -- Posted via http://www.ruby-forum.com/.