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!
on 2008-11-13 12:48
on 2008-11-13 13:13
On Thu, Nov 13, 2008 at 12:45 PM, sa 125 <email@example.com> 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.
on 2008-11-13 13:35
That's exactly what I needed -- I completely forgot about the self.method in the definition. Thanks!