2015-03-31 38 views
-1

是否有可能在的if,elsif的列表中找到一個字符串?gets.chomp在列表中找到一個字符串

def number_problem() 

    puts "Please enter a number 1-100 for a phrase or word back!" 
    number = gets.chomp 

    mult_of_three = ["3", "6", "9", "12", "15", "18", "21", "24", "27", "30", "33", "36", "39", "42", "45", "48", "51", "54", "57", "60", "63", "66", "69", "72", "75", "78", "81", "84", "87", "90", "93", "96", "99"] 
    mult_of_five = ["5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"] 
    mult_of_both = ["15", "30", "45", "60", "75", "90"] 

    if number == mult_of_three 
    puts "Bit" 

回答

0

要查找數組中是否存在元素,可以使用include?。這裏:

if mult_of_three.include?(number) 

實施例:

number = gets.chomp 
36 
# => "36" 

mult_of_three.include?(number) 
# => true 

number = gets.chomp 
98 
# => "98" 

mult_of_three.include?(number) 
# => false 
相關問題