验证数组中是否存在元素

时间:2014-08-06 17:56:38

标签: 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) : " 
        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)

问题是我输入了一个假值(不在数组中),程序继续下一步。

如何解决问题?

感谢您的回答。

2 个答案:

答案 0 :(得分:0)

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

您应该使用while or until代替unless

def verify(list,valueUser,stepN)
  until 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.chomp
  end
  puts stepN
  valueUser
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.chomp

geekTypeUser = verify(geekTypes,geekTypeUser,stepTwo)

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

答案 1 :(得分:0)

试试这个:

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 ...