在Class中调用方法

时间:2016-06-03 08:57:50

标签: ruby-on-rails ruby

我是红宝石的新手,所以这段代码不起作用,请为我提供在课堂上调用方法的正确方法

Class TestClass

  def testMethod
    puts "hello"
  end

  testMethod
end

更新

大家好,感谢所有的帮助和评论,就像@Stefan和@Matt说的那样,我的例子非常罕见地使用这种方式并且感谢给出了正确的路径我只是想从我的问题中添加这个并且我发现一种工作方式

class TestClass
    def self.testMethod
       puts "hello"
    end

    TestClass.testMethod
end

3 个答案:

答案 0 :(得分:1)

class TestClass
    # a class method
    def self.test_method
       puts "Hello from TestClass"
    end

    # an instance method
    def test_method
       puts "Hello from an instance of TestClass"
    end
 end

 # call the class method
 TestClass.test_method


 # create and instance object of TestClass
 instance_of_TestClass = TestClass.new

 # call the instance method of the new object
 instance_of_TestClass.test_method

答案 1 :(得分:0)

你必须在课堂上调用方法,如:

class TestClass

  def testMethod
     puts "hello"
  end
  def test_2
    testMethod
  end
end

object = TestClass.new()
puts object.test_2

答案 2 :(得分:-1)

您的示例使用实例方法定义类。然后尝试从类中调用实例方法 - 这不起作用。

相反,您需要在实例中调用方法,或将其转换为类方法。

class TestClass

  def self.testMethod
     puts "hello"
  end

  testMethod 
end

实例和类级别的区别是一个基本概念,您可以从参加一些教程中受益,首先阅读http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/