如何获取用户输入并检查数组中的项目?

我希望用户输入他们的胡须风格,然后我将它与一系列胡须样式的胡须进行核对。 这是我想做的额外事情,我不知道如何解决。 我接触到的唯一项目是(包括?),但我想要:

(数组名称).include? (从用户输入的值)

require_relative 'list_of'
require_relative 'error'


#User inputs a value
def get_beard
    puts "What style of beard do you have?"
    beard = gets
    if check_beard_ok?(beard)
        then no_problem(beard) end  
end

#Value passed to check length doesn't exceed 25 letters
def check_beard_ok?(beard)

    # while beard.length < 25
        # beard.in?(beard_style)
    # end
end


#The value is printed here without any errors occuring
def no_problem(beard)
    puts "nYou have a " + beard
    puts "nThere are other beards that you could try like..."
    list_of
end

get_beard

看看这个http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F

你可以做

breads = [ "Banana bread", "Beer bread", "Pumpernickel" ]
  breads_selected = [ "Banana bread"]
  if breads.include?(breads_selected) 
    # this is true
  end
  unless  breads.include?(breads_selected) 
    # this is false
  end

beards = ['long','short','ginger','dirty']
selected = ['ginger']
selected - beards
=> []

(选定的胡须)将从胡须中不存在的所选元素中返回元素。 生姜在列表中,所以我们得到一个空阵列。

beards = ['long','short','ginger','dirty']
selected = ['ginger', 'fluffy']
selected - beards
=> 'fluffy'

我的第二个例子返回蓬松,因为它不在列表中。 你可以将它封装在自己的方法中,检查返回的数组是否为空。

这种方法非常棒,因为您不仅可以检查所选元素是否存在,还会返回那些不存在的元素,如果您想要返回某种有意义的错误,这会很有帮助。

链接地址: http://www.djcxy.com/p/25689.html

上一篇: How to get the users input and check against the items in an array?

下一篇: Check if array element appears on line