1
class AiClassGame
    def calculate_cpuNum(sum)
        if sum <= 79
            cpuNum = 80 - sum
        elsif sum <= 88
            cpuNum = 89 - sum
        else
            cpuNum = 100 - sum
        end
        #puts 'calculate method'
    end


calculate_cpuNum is the method i get the error for calling

if sum >= 71
        calculate_cpuNum(sum)
    else
        sum += cpuNum
        checkPlayer = false
        puts 'sum = ' + sum.to_s
        break if sum >= 100
    end
    puts 'Computer has choosen : ' + cpuNum.to_s, 'sum = ' + sum.to_s
end

I get the error

ai_class_game.rb:39 in <class:AiClassGame>: undefined methodcalculate_cpuNum` for AiClassGame:Class (NoMethodError)from ai_class_game.rb:7:in `<main>`
2
  • 2
    At the very least you'll have to provide us with a stacktrace from the error. Sep 2, 2012 at 22:00
  • it only gives this at the stack trace: ai_class_game.rb:40:in <class:AiClassGame>' ai_class_game.rb:7:in <main>' line 7 is the class .... line 40 is the method call
    – MRifat
    Sep 2, 2012 at 22:38

1 Answer 1

2

You define calculate_cpuNum as an instance method of the AiClassGame class. However the code in which you call the method is written directly in the class body - not inside an instance method.

The only methods you can call (without an explicit receiver) from within the class body are class methods. Instance methods can only be called from other methods of the same class or by calling them on an object of the given class using my_ai_class_game_object.calculate_cpuNum.

I should also point out that it's highly unusual to write your code directly inside the class body like that.

Another unrelated error that you have in your code is that you're using the cpuNum variable outside of the calculate_cpuNum method. cpuNum is a local variable and can not be used outside of the method in which you defined it.

1
  • Thanks for answering, am new at ruby programming, i'll make sure not to write it directly inside the class body, thanks for the advice
    – MRifat
    Sep 2, 2012 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.