A class object (like Ticket) has its own methods, its own state, its own identity. It doesn’t share these things with instances of itself.
我们可以把Class Method看作是class自己的Singleton Method. Class是制造object的工厂,工厂当然可以有自己的method啊!这些method是不给object的。
In referring to Ruby methods outside of code, it’s customary:
1, to refer to instance methods by naming the class in which they are defined, followed by a hash mark (#), and the name of the method;
2, to refer to class methods with a similar construct but using a period (.).
Sometimes you’ll see a double colon (::) instead of a period in the class method case.
我要求自己严格遵循:
Instance Method of a class写成:Ticket#show_price
Class Method of a class写成:Ticket::show_most_expensive
Class Constant
We refer to the constant from outside the class definition using a special path notation: a double colon (::).
class Ticket
VENUES = ["Convention Center", "Fairgrounds", "Town Hall"]
end
$ puts "We've closed the class definition."
$ puts "So we have to use the path notation to reach the constant."
$ puts "The venues are:"
$ puts Ticket::VENUES
The double-colon notation pinpoints the constant VENUES inside the class known by the constant Ticket, and the list of venues is printed out.
Thursday, March 15, 2007
Refer to Class Method and Class Constant from outside of the class definition
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment