Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method (NoMethodError) ruby

I keep getting the following error message:

text.rb:2:in `<main>': undefined method `choices' for main:Object (NoMethodError)

But I can't seem to understand why my method is "undefined":

puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp 
choices(users_choice)

def choices (choice)    
   while choice != 'q'      
        case choice

        when '1' 
            puts "you chose one!"

        when '2'
            puts "you chose two!"

        when '3'
            puts "you chose three!"
        end     
   end 
end
like image 889
stecd Avatar asked Jan 12 '14 07:01

stecd


People also ask

What is an undefined method in Ruby?

Undefined method call created a NoMethodError. This is a typical Ruby error that indicates that the method or attribute you are attempting to call on an object has not been declared.

What does NoMethodError mean?

According to The 2022 Airbrake Error Data Report, the NoMethodError is the most common error within projects. As clearly indicated by the name, the NoMethodError is raised when a call is made to a receiver (an object) using a method name that doesn't exist.

How do you check if a function is undefined in Ruby?

Undefined instance variables are always nil , so you want to check for that. Try the “safe navigator operator” (Ruby 2.3+) which only calls a method if the variable is not nil .

What does undefined method for nil NilClass mean?

The Undefined method for nil:NILClass occurs when you attempt to use a formula on a blank datapill. This indicates that the datapill was not provided any value at runtime.


2 Answers

This is because you are calling method choices, before defining it. Write the code as below:

puts "Select [1] [2] [3] or [q] to quit"
users_choice = gets.chomp 

def choices (choice)    
  while choice != 'q'      
    case choice
    when '1' 
      break  puts "you chose one!"
    when '2'   
      break puts "you chose two!"
    when '3'
      break  puts "you chose three!"
    end     
  end 
end

choices(users_choice)

I used break, to exit from the while loop. Otherwise it will create an infinite loop.

like image 90
Arup Rakshit Avatar answered Sep 30 '22 14:09

Arup Rakshit


def main
puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp
choices(users_choice)
end

def choices (choice)
  while choice != 'q'
    case choice

      when '1'
        puts "you chose one!"
        break
      when '2'
        puts "you chose two!"
        break
      when '3'
        puts "you chose three!"
        break
    end
  end
end

main

The method only needs to be called prior to being executed. Here I wrap the definition in the main method, but only call main after the definition of choices().

like image 25
Marc Mance Avatar answered Sep 30 '22 16:09

Marc Mance