【问题标题】:Method exists but Ruby says it is undefined方法存在,但 Ruby 说它是未定义的
【发布时间】:2020-06-09 12:29:24
【问题描述】:

我目前是 Ruby 的初学者,我目前正忙于一项任务。我正在重新制作 ruby​​ 的策划者。但是,我很难完全理解语法。当我尝试调用该方法时,它告诉我它是未定义的。我尝试在这里阅读其他一些问题,但没有一个解决方案对我有帮助,因为我的问题有点不同。 我先上课了:

class Mastermind

然后我在里面做了方法。

        def check
        result=Array.new(4)
        i=0
        while i<5
          if chooseWord[i]==userAnswer[i]
            result[0]="exact"
            i=i+1
          end
          puts result[0]
        end
        checkingResult=check.new
      end

  def userAnswer
    puts "What is your guess? "
    word = gets.chomp
    guess="Your guess was #{word}"
    userAnswer=guess.chars.to_a
    return userAnswer
  end

  def chooseWord
    lines = File.readlines("02-word-list.txt" )
    chosen=lines.sample
    puts chosen
    chooseWord=chosen.chars.to_a
    return chooseWord
  end

然后我在类中调用了我想要的方法。

check.method

我得到的错误:

undefined local variable or method `check' for Mastermind:Class (NameError)

但也在它之外只是为了看看是否有任何变化,它没有。对不起,如果这也是一个愚蠢的问题,但我很困惑。我希望我的方法表现得像 void 方法,然后在有意义的情况下被调用。

【问题讨论】:

    标签: ruby methods


    【解决方案1】:

    然后我在类中调用了我想要的方法。

    check.method
    

    似乎您试图通过以下方式调用类体内的方法:

    class Mastermind
      def check
        # ...
      end
    
      check.method
    end
    

    首先,调用方法不必附加.method,直接写方法名即可。

    但是在类体内调用check 也不起作用,因为check 是一个instance 方法。为了调用它,你必须先创建一个实例,例如:

    mm = Mastermind.new
    mm.check
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2021-07-30
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2019-12-25
      相关资源
      最近更新 更多