class methods are defined with `self.foo` rather than `class.foo` - so
that
def class.overall_class_method
"overall total on class"
end
should be written:
def self.overall_class_method
"overall total on class"
end
Peter's example nicely demonstrates two ways of calling a method
defined in one class from another - either creating an instance of the
first class within the second and then calling the instance method on
it, or by defining the method in the first class as a class method,
rather than an instance method - allowing you to call it directly
without creating an instance of the first class.
1 module Checkout
2 extend self
3
4 def overall_method
5 "overall total #{self.class}"
6 end
7 end
8
9 class Shopping
10 include Checkout
11
12 def order
13 puts overall_method
14 puts Checkout.overall_method
15 end
16 end
overall total Shopping
overall total Module
I just tried this and works D:
I was trying to define one method that i can use
as a class and instance one.
PD: I have to see more often this list
···
2011/12/11 Peter Vandenabeele <peter@vandenabeele.com>
On Sun, Dec 11, 2011 at 2:32 PM, jake kaiden <jakekaiden@yahoo.com> wrote:
> hey folks,
>
> class methods are defined with `self.foo` rather than `class.foo` - so
> that
>
> def class.overall_class_method
> "overall total on class"
> end
>
> should be written:
>
> def self.overall_class_method
> "overall total on class"
> end
>
Sorry for the confusion ... (hits hammer on head: _always_ test code before
posting)