llamingo
llamingo

Reputation: 77

Method exists but Ruby says it is undefined

I am currently a beginner at Ruby and I am currently stuck with an assignment. I am remaking mastermind in ruby.However, I am struggling to understand the syntax completely.When I try to call the method it tells me it is undefined. I tried reading through some other questions here but none of the solutions helped me as my problem is a bit different. I made a class first:

class Mastermind

Then I made the methods inside it.

        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

And after that I called the method I wanted inside the class.

check.method

The error I get:

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

But also outside of it just to see if anything changes which it didn't. Sorry if this is a stupid question as well but I am very confused. I wanted my methods to act like void methods and then be called if that makes sense.

Upvotes: 1

Views: 919

Answers (1)

Stefan
Stefan

Reputation: 114248

And after that I called the method I wanted inside the class.

check.method

Seems like you tried to call the method within the class body via:

class Mastermind
  def check
    # ...
  end

  check.method
end

First of all, you don't have to append .method to call a method, just write the method's name.

But calling check within the class body doesn't work either because check is an instance method. In order to call it, you have to create an instance first, e.g.:

mm = Mastermind.new
mm.check

Upvotes: 4

Related Questions