Search code examples
rubyclass-methodinstance-methods

Calling an instance method from a class method


I have this class:

class MyClass
@@variable = 9
    def initialize
        @@variable -= 1
    end 
    def self.tracker
        puts @@variable
        if @@variable <9
            puts "#{action}"
        end
    end

    def action
        puts "The number is less than 9!"
    end    
end 

And when I try to call the class method:

MyClass.tracker

I keep getting this error:

`tracker': undefined local variable or method `action' for MyClass:Class (NameError)

Is it not possible to call an instance method from a class method or vice versa? Am I doing something wrong?


Solution

  • In order to call an instance method you need to create an instance of the object. In ruby calling 'new' creates an instance of a class.

    You can change this line

    puts "#{action}"
    

    To this:

    puts "#{new.action}"
    

    .new inside of the class will make a new instance of the class you are in. Which will also run your initialize and decrease @@variable by one. The way the class is written right now we never past if @@variable <9 unless you are making instances of the class outside of the code you shared.

    Overall this is a pretty odd class. It isn't common to use class variables like this. It is much more common to create an instance of a class, use instance variables/methods to house your logic.