加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

未定义的方法(NoMethodError)ruby

发布时间:2020-12-17 04:23:25 所属栏目:百科 来源:网络整理
导读:我一直收到以下错误消息: text.rb:2:in `main': undefined method `choices' for main:Object (NoMethodError) 但我似乎无法理解为什么我的方法是“未定义的”: puts "Select [1] [2] [3] or [q] to quit"; users_choice = gets.chomp choices(users_choic
我一直收到以下错误消息:
text.rb:2:in `<main>': undefined method `choices' for main:Object (NoMethodError)

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

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

解决方法

这是因为您在定义方法之前调用方法选择.编写如下代码:
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)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读