Ruby:未定义的方法错误

时间:2012-02-07 03:20:35

标签: ruby

我有这个用Ruby编写的代码,但是当我尝试用irb测试我的文件时,我收到了:NoMethodError: undefined method 'find_displacement' for SymbolTable:Class。我在这里做错了什么?

class SymbolTable
  include Singleton

  @@MAX_SYMBOLS  = 500
  @@DISPLACEMENT = SymbolTable.find_displacement()   ##error here
  @@TABLE_SIZE   = @@MAX_SYMBOLS + (@@MAX_SYMBOLS * 0.1) + @@DISPLACEMENT

  def initialize()
    "Constructs a single instance of a SymbolTable to be used by the compiler"
      @sym_table = Array.new(@@TABLE_SIZE)
  end

  def add(element, index)
    "Inserts an element (identifier) into the SymbolTable"
    @sym_table[index] = element if element.is_a? SymbolTableEntry
  end

  def SymbolTable.find_displacement()
    n = 1
    k = @@MAX_SYMBOLS
    while not (k + n).odd? do
      n += 2
    end

    return k + n
  end

  def to_s
    "Prints a list of all elements currently in the SymbolTable"
    pp @sym_table
  end
end

1 个答案:

答案 0 :(得分:4)

您必须在调用之前定义方法。

在设置类变量时,尚未定义任何单例方法。