Forum: Ruby Using Class methods

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-13 12:48
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!
E088bb5c80fd3c4fd02c2020cdacbaf0?d=identicon&s=25 Jesús Gabriel y Galán (Guest)
on 2008-11-13 13:13
(Received via mailing list)
On Thu, Nov 13, 2008 at 12:45 PM, sa 125 <s_ayalon@hotmail.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.
7db3b1680807d393d40260591b4ae5e0?d=identicon&s=25 sa 125 (sa125)
on 2008-11-13 13:35
That's exactly what I needed -- I completely forgot about the
self.method in the definition. Thanks!
This topic is locked and can not be replied to.