Curt Sampson schrieb:
I'd understood to mean you were defining stuff in the "top-level module."
Well, it's really the top-level class (i.e., Object), right? But then,
def hello
puts "hello"
end
This defines a private instance method of Object. You define the method without specifying a class, just like a procedure in a non-OO language. Because it is defined in Object, you can call it everywhere:
hello
class X
hello
def m
hello
end
end
You can really treat it like a standalone procedure. But you cannot treat it like an object's method, because it is private. Private methods can only be called without specifying the receiver of the method.
"foo".hello # => error, private method...
There's a trick for calling private methods, though:
"foo".send( :hello ) # => hello
The method is there (inherited from Object), but it is private. This is a clever way to be able to either write procedural or OO code and to even use both together.
class Object
def goodbye
puts "goodbye"
end
This defines a public (per default) instance method of Object.
Object.new.goodbye # prints "goodbye"
Send the message to a new object, which inherits the (public) method "goodbye" from Object (as all objects do).
goodbye # prints "goodbye"
Send the message to self, the top level object (main). This is an Object, so it inherits method "goodbye" from Object, too.
class Object
hello # prints "hello"
end
Send the message to the class Object. Since classes are instances of Object in Ruby, even the class Object inherits method "goodbye" from Object.
Object.new.hello # private method `hello' called for #<Object:...
Send the message to a new object. The object inherits method "hello" from Object, but it is a private method, so it can't be called with an explicit receiver.
I dunno; a lot of my predictions about what should happen in Ruby don't
work out very well.
When learning Ruby, I made the experience that most of the times the code I wrote just worked. Without thinking about the language's internals I wrote some kind of pseudocode in Ruby syntax and more than often found that I just could run it. Sometimes I really was surprised that the code I had written was working, and I thought "how is Ruby doing this?" Then I started to experiment with the language and I had many surprises, but it finally made sense most of the times, at least for me. I got the most POLS out of Ruby when not thinking about Ruby.
I wish that there were a two-page document somewhere explaining just the
language syntax itself that would, if read very carefully, explain all
of this.
I don't think that the syntax alone would have helped you in this case.
Regards,
Pit