Ruby未定义的辅助方法

时间:2011-01-15 06:03:45

标签: ruby

我正在编写一个简单的ruby脚本。我希望在运行脚本时显示帮助消息。

def myClass
    def help
        puts "Help message"
    end

    (...other methods...)

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

当我运行它时,我得到“myClass:Class(NameError)”的“未定义的局部变量或方法'帮助'”。红宝石为什么不看我的帮助方法?红宝石失去了吗?它已经定义了!我无法进一步定义它!

1 个答案:

答案 0 :(得分:1)

你需要定义一个类方法,你有一个实例方法。

class MyClass   
  def self.help
    puts "help"   
   end

  help

end

澄清一点

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
相关问题