Hi --
open methed is a method defined in kernel module
Thank you for the quick response. I see that now but I guess my
underlying questions still remains. What should indicate that the
method is part of Kernel and why is it invoked when I call 'File.open'?
It isn't; the method that's invoked is IO.open. Here's a (very)
schematic version of what's going on:
module Kernel
def open(*args)
# do one of these:
IO.open(args)
# or
IO.popen(args)
# depending on presence of pipe character
end
private :open
end
class IO
def IO.open(*args)
io_object = new
# now do some logic branching, depending on whether
# or not a code block is present in the method call
return io_object
end
end
class File < IO
end
Now, note the following:
Kernel#open is a private instance method of Kernel. That means that
*every* Ruby object can see that method. It also means (for reasons I
won't go into here, but that are in my book that you can only ever
call it *without* an explicit receiver:
some_random_object.open(...) # no good: trying to call private
# method "open"
open(...) # OK, because no receiver present
If IO.open didn't exist, then when you did:
IO.open(...)
Ruby would think you were trying to call the private Kernel method
"open". But in fact you're not, because there's a new and separate
open method defined as a class method in IO.
Finally, File.open works because, as a subclass of IO, File gets to call
IO's class methods. File.open, like IO.open, is not the same as the
generic, private open method provided by the Kernel module.
You can even show this in action, by overriding Kernel#open. (This
will create a public version of it, so I won't get the error message
about calling a private message.)
irb(main):001:0> module Kernel; def open; "Hello!"; end; end
=> nil
irb(main):002:0> 1.open
=> "Hello!"
irb(main):003:0> "some string".open
=> "Hello!"
irb(main):004:0> IO.open
ArgumentError: wrong number of arguments (0 for 1)
Well, I got an error on IO.open, but that shows that the method being
called was IO.open, and not the new version of Kernel#open.
David
···
On Mon, 27 Nov 2006, Patrick McNally wrote:
--
David A. Black | dblack@wobblini.net
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org