2

我希望用户输入他们的胡须风格,然后我将根据一系列胡须风格中的胡须列表对其进行检查。这是我想做的额外事情,我不知道如何解决。我遇到的唯一一项接近它的东西是(包括?)但我想拥有:

(数组名).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
4

2 回答 2

0

take a look at this http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F

you can do

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
于 2013-10-03T13:28:13.753 回答
0
beards = ['long','short','ginger','dirty']
selected = ['ginger']
selected - beards
=> []

(selected - beards) 从 selected 中返回 beards 中不存在的元素。Ginger 在列表中,所以我们得到一个空数组。

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

我的第二个示例返回 fluffy 因为它不在列表中。您可以将其包装在它自己的方法中,以检查返回的数组是否为空。

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

于 2018-01-11T10:30:29.487 回答