# Using Class methods

**URL:** <https://www.ruby-forum.com/t/using-class-methods/153208>\
**Category:** Ruby\
**Created:** [November 13, 2008, 12:48pm UTC](https://www.ruby-forum.com/t/using-class-methods/153208 "2008-11-13T12:48:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sa125](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@sa125](https://www.ruby-forum.com/u/sa125)\
**Post date:** [November 13, 2008, 12:48pm UTC](https://www.ruby-forum.com/t/using-class-methods/153208/1 "2008-11-13T12:48:43Z")

</div>

Hi - I’m new to ruby and trying to write some classes to help me with my  
work. What I’m trying to figure out is how to access the class methods  
from other files. Say that my class is

Class Example

$glob\_1

def method\_1  
#…  
end

def method\_2  
#…  
end

end

Then in another file (same dir) I’d do:

require ‘example’

f = example.method\_1

Is this correct?

Also, I want to test my class - where do I add the:

if **FILE** = $0  
method\_1  
method\_2  
end

Thanks!

---

<div class="post-metadata">

**Author:** ![sa125](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@sa125](https://www.ruby-forum.com/u/sa125)\
**Post date:** [November 13, 2008, 1:35pm UTC](https://www.ruby-forum.com/t/using-class-methods/153208/2 "2008-11-13T13:35:45Z")

</div>

That’s exactly what I needed – I completely forgot about the  
self.method in the definition. Thanks!

---

<div class="post-metadata">

**Author:** ![sa125](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@sa125](https://www.ruby-forum.com/u/sa125)\
**Post date:** [November 13, 2008, 1:13pm UTC](https://www.ruby-forum.com/t/using-class-methods/153208/3 "2008-11-13T13:13:14Z")

</div>

On Thu, Nov 13, 2008 at 12:45 PM, sa 125 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> end
> 
> f = example.method\_1
> 
> Is this correct?

Did you try it?  
It won’t work. There are several reasons. Class methods are defined like  
this:

class Example  
def self.method1  
puts “method1”  
end

def Example.method2  
puts “method2”  
end

class \<\< self  
def method3  
puts “method3”  
end  
end

end

Then in your other file, the require is fine (if the file is called  
example.rb).  
But the class methods have to be invoked on the class object, which is  
assigned  
to the constant after the word class. So it’s Example with capital E.

require ‘example’

Example.method1

> Also, I want to test my class - where do I add the:
> 
> if **FILE** = $0  
> method\_1  
> method\_2  
> end

It’s usually added at the end of the file, after the class is defined.  
Also here you will need to call the methods as Example.method\_1

Hope this helps,

Jesus.
