Ruby 验证数组中是否存在元素

Ruby 验证数组中是否存在元素,ruby,Ruby,我想验证数组中是否存在元素 这是我的密码: 我创建了一个函数来验证用户输入的值是否存在: def verify(list,valueUser,stepN) unless list.include?(valueUser) puts "It is not a valid Geek Type !" puts "Type the code of your Geek type (ex : GB for Geek of Business) : " v

我想验证数组中是否存在元素

这是我的密码:

我创建了一个函数来验证用户输入的值是否存在:

def verify(list,valueUser,stepN)
    unless list.include?(valueUser)
        puts "It is not a valid Geek Type !"
        puts "Type the code of your Geek type (ex : GB for Geek of Business) : " 
        valueUser = gets
    else
        puts stepN
    end
end 
我创建我的数组:

geekTypes = [ "GB", "GL", "GC", "GMC", "GCA", "GM", "GCM", "GMD", "GCS", "GMU", "GCC", "GPA", "GE", "GP", "GED", "GS", "GFA", "GSS", "GG", "GTW", "GH", "GO", "GIT", "GU", "GJ", "G!", "GLS", "GAT"]
然后我调用我的函数:

puts "Type the code of your Geek type (ex : GB for Geek of Business) : " 
geekTypeUser = gets

verify(geekTypes,geekTypeUser,stepTwo)
问题是,即使我键入了一个不在数组中的假值,程序也会继续执行下一步

我如何解决我的问题


谢谢你的回答。

如果我理解你想做什么-问题是你的代码中没有循环。无论输入是否有效,该方法都会在检查另一个输入之前退出

您应该使用而不是,除非:

请注意,我是在gets之后添加的,否则,您的代码将收到以新行GB结尾的输入\n而不是GB

geekTypes = ["GB", "GL", "GC", "GMC", "GCA", "GM", "GCM", "GMD", "GCS", "GMU", "GCC", "GPA", "GE", "GP", "GED", "GS", "GFA", "GSS", "GG", "GTW", "GH", "GO", "GIT", "GU", "GJ", "G!", "GLS", "GAT"]

loop do
  print "Type the code of your Geek type (ex : GB for Geek of Business) : "
  geekTypeUser = gets
  break if geekTypes.include?(geekTypeUser)
  puts "It is not a valid Geek Type !"
end

... continue to next step ...

你确定不是在第二次输入之后?
geekTypes = ["GB", "GL", "GC", "GMC", "GCA", "GM", "GCM", "GMD", "GCS", "GMU", "GCC", "GPA", "GE", "GP", "GED", "GS", "GFA", "GSS", "GG", "GTW", "GH", "GO", "GIT", "GU", "GJ", "G!", "GLS", "GAT"]

loop do
  print "Type the code of your Geek type (ex : GB for Geek of Business) : "
  geekTypeUser = gets
  break if geekTypes.include?(geekTypeUser)
  puts "It is not a valid Geek Type !"
end

... continue to next step ...