I have a file like this;
class File
class << self
def diff
#some stuff--------------
end
end
end
def method_1
#-----------
end
def method_2
#------------
end
method_1
method_2
now ,I need to rewrite this file.
but I don’t how to deal with the class File…
one.
+++++++++++++++++++
class File
class << self
def diff
#some stuff--------------
end
end
end
class Myclass
def method_1
end
def method_2
end
end
++++++++++++++++++++
two
++++++++++++++++++++
class Myclass
class File
class << self
def diff
#some stuff--------------
end
end
end
def method_1
end
def method_2
end
end
+++++++++++++++++++++
so, which way should I use?
any thought will be appreciated.
On 10.07.2009 04:01, Zhenning G. wrote:
def method_1
end
end
end
def method_1
end
def method_2
end
end
+++++++++++++++++++++
That’s difficult to answer since we cannot see how your method_1 and
method_2 use class File.
In the general case inheritance is done like this:
class A
end
class B < A
end
B is now subclass of A.
Kind regards
robert
At 2009-07-09 10:01PM, “Zhenning G.” wrote:
I have a file like this;
class File
class << self
def diff
#some stuff--------------
end
end
end
How is that different from
class File
def diff
#some stuff--------------
end
end
?
Still learning…
Hi –
On Fri, 10 Jul 2009, Glenn J. wrote:
How is that different from
class File
def diff
#some stuff--------------
end
end
?
Still learning…
The construct:
class << object
# …
end
puts you into a class definition block for the singleton class of
object. The singleton class is where the methods are defined that are
specific to that exact object (as opposed to those that the object
gets from its class).
In this case:
class File
class << self
“self” is the class object File (because when you’re in a class
definition block, “self” is set to the class object). The methods
defined in the inner definition block will be callable only directly
on File itself (and its subclasses; classes get to share their
singleton methods with their subclasses)[1]. So you’ll be able to do:
File.diff
but not
f = File.new(…)
f.diff # wrong; it’s not an instance method
If you do
class File
def diff
then you’re defining an instance method.
For more info, see http://www.wobblini.net/singletons.html. (And for a
lot more info, see http://www.manning.com/black2 
David
[1] And singleton methods of class objects are more commonly referred
to as “class methods”.