Ruby noob
Ruby noob

Reputation: 507

Ruby undefined helper method

I am writing a simple ruby script. I want a help message to be displayed when the script is run.

def myClass
    def help
        puts "Help message"
    end

    (...other methods...)

    help
    # main loop
    (...rest of script...)
end

When I run it, I get "undefined local variable or method 'help' for myClass:Class (NameError)". Why doesn't ruby see my help method? Did ruby lose it? It's already defined! I can't define it any further!

Upvotes: 0

Views: 239

Answers (1)

jshen
jshen

Reputation: 11907

you need to define a class method, what you have there is an instance method.

class MyClass   
  def self.help
    puts "help"   
   end

  help

end

To clarify a bit

class MyClass
  def self.my_class_method
    puts 'class method'
  end

  def my_instance_method
    puts 'instance method'
  end
end

# class methods are called on teh class itself
MyClass.my_class_method

# instances methods are available on instances of the class
obj = MyClass.new
obj.my_instance_method

Upvotes: 1

Related Questions