Using Class methods

S

sa 125

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!
 
J

Jesús Gabriel y Galán

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?

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.
 
S

sa 125

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top