How to call a method from a different class

Hi all,

I am currently stuck trying to call a method from a different class.

example…

I have a checkout class and within it I have the overall method, I want
to call the overall method from within the shopping class…

Thanks in advance.

On Sat, Dec 10, 2011 at 10:47 PM, Darren H. [email protected] wrote:

Hi all,

I am currently stuck trying to call a method from a different class.

example…

I have a checkout class and within it I have the overall method, I want
to call the overall method from within the shopping class…

So that could be done like this.

# caveat : untested code class Checkout

def overall_instance_method
“overall total on instance”
end

def class.overall_class_method
“overall total on class”
end

end

class Shopping

def order
# prepare order

# with a Checkout instance
checkout = Checkout.new
puts checkout.overall_instance_method

# with class method on Checkout
puts Checkout.overall_class_method

end

end

HTH,

Peter

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

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.

if you make the change noted above, and add…

s = Shopping.new
s.order

…to the end, you’ll see the expected output.

  • j

On Sun, Dec 11, 2011 at 2:32 PM, jake kaiden [email protected]
wrote:

def self.overall_class_method
“overall total on class”
end

Sorry for the confusion … (hits hammer on head: always test code
before
posting)

Peter

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 :slight_smile:

2011/12/11 Peter V. [email protected]

Peter


*

Francesco Rodrguez
*

**
*

@frodsan http://twitter.com/#!/frodsan

https://github.com/frodsan
**

http://frodsan.wordpress.com/
*
*

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs