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
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.
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.
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 .
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.
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With