Hi --
Before someone showed me
method(:puts).class
I thought methods are no objects.
But class Method seems to exist, with
Method.class giving back Class,
so
Method.class.new
would be the same as
Class.new
I guess one can extend every Class.new via
.instance_eval, but my problem here fundamentally is,
why is a method an object? And if I can create a
new object from any method...
What I now see is that every object in ruby has methods,
which are objects as well. Did I make a mistake? Are methods
no objects? Or why are methods objects too?
Methods can be objectified, so to speak. Each Method object is a kind
of wrapper around a method. The methods themselves are not first-class
objects.
You can see the wrapper effect by comparing object ids:
method(:puts).object_id
=> 1317360
method(:puts).object_id
=> 1310220
There's no Method.new; you have to get a Method object via an object.
You can unbind a method from a given object and bind it to another
(within certain rules, mainly having to do with class):
"abc".method(:split).unbind.bind("def").call(//)
=> ["d", "e", "f"]
Another point I'd make is that objects don't really have methods.
Classes and modules contain method definitions; objects have the
intelligence to go looking for method definitions, along a
predetermined class/module path, when they receive messages. I know
that sounds like a wordy way to put it (and there's nothing wrong with
saying that an object "has" methods, informally), but it becomes
important when you get deeply into the way classes and modules and
message resolution work.
David
···
On Tue, 23 Jun 2009, Marc Heiler wrote:
--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2\)
"Ruby 1.9: What You Need To Know" Envycasts with David A. Black
http://www.envycasts.com