【问题标题】:Rake NoMethodError: undefined method 'scan' for Lexicon:ClassRake NoMethodError:Lexicon:Class 的未定义方法“扫描”
【发布时间】:2015-01-01 09:32:32
【问题描述】:

当我尝试使用以下 RakeFile 运行 rake 测试时,我收到 NoMethodError: undefined method 'scan' for Lexicon:Class

require './lib/ex48/lexicon.rb'
require 'test/unit'

class TestLexicon < Test::Unit::TestCase

    def test_directions
        assert_equal(Lexicon.scan('north'), [%w(direction north)])
    end

end

我有一个简单的 Lexicon 类:

class Lexicon

  def initialize
    @direction = %w(north south east west down up left right back)
    @verbs = %w(go stop kill eat)
    @stop_words = %w(the in of from at it)
    @nouns = %w(door bear princess cabinet)
    @numbers = (0..9)
  end

  attr_reader :direction, :verbs, :stop_words, :nouns, :numbers

  def scan(input)
    words = input.split
    result = []

    words.each do |word|
      if @direction.include? word
        result.push ['direction', word]
        next
      end

      if @verbs.include? word
        result.push ['verb', word]
        next
      end

      if @stop_words.include? word
        result.push ['stop', word]
        next
      end

      if @nouns.include? word
        result.push ['noun', word]
        next
      end

      result.push ['number', word] if @numbers.include? word
    end

    result
  end

end

我想看看扫描方法是否有效。我正在学习 Ruby,所以我是该语言的新手,这是我的第二次 RakeFile 测试。我做错了什么?

【问题讨论】:

    标签: ruby rake nomethoderror


    【解决方案1】:

    def self.scan 为了使该方法成为一个类,而不是实例方法(在类的实例上调用)。或者干脆使用Lexicon.new(args).scan

    【讨论】:

    • self.scan 不起作用,因为我需要初始化实例变量。但是,正如你所说,我忘记实例化 Lexicon 了。执行lexicon = Lexicon.new 然后将每个Lexicon 调用为lexicon 使测试成功。非常感谢你!我犯了一个愚蠢的错误。
    • 你如何使用构造函数(初始化)有点奇怪——其中的数据集是恒定的,它不会从一个实例变为另一个实例。我会将其拉入类 Lexicon 中的常量中,并使 scan 方法成为一类。
    • 谢谢!我会这样做的。
    • 供将来参考,此 OP 问题源自 learnrubythehardway.org/book/ex48.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多