Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...