未定义的方法(NoMethodError)ruby

ste*_*ecd 7 ruby nomethoderror

我一直收到以下错误消息:

text.rb:2:in `<main>': undefined method `choices' for main:Object (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

但我似乎无法理解为什么我的方法是"未定义的":

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
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 16

这是因为您choices在定义之前调用方法.编写如下代码:

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)
Run Code Online (Sandbox Code Playgroud)

我用过break,退出while循环.否则它将创建一个无限循环.