如何调用类之外的方法

rub*_*ist 1 ruby ruby-on-rails

我怎么会打电话myfuncmyotherfunc下面的类之外?

class Accounting::Invoice < ActiveRecord::Base
  def myfunc
    return true
  end

  class << self
    def myotherfunc
      return false
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Dav*_*son 8

myfunc是一个实例方法,所以你首先需要一个实例然后你可以调用该函数:

invoice = Accounting::Invoice.new
invoice.myfunc
Run Code Online (Sandbox Code Playgroud)

myotherfunc类方法,所以你只需要在类对象上直接调用它:

Accounting::Invoice.myotherfunc
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这个答案并不是Rails特有的; 它适用于任何Ruby程序.

这篇文章可能会有所帮助(我没有阅读整篇文章):http: //railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/