【问题标题】:How to get the users input and check against the items in an array?如何获取用户输入并检查数组中的项目?
【发布时间】:2013-10-09 20:17:44
【问题描述】:

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

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

【问题讨论】:

    标签: ruby arrays search input


    【解决方案1】:

    看看这个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
    

    【讨论】:

      【解决方案2】:
      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,因为它不在列表中。您可以将其包装在它自己的方法中,以检查返回的数组是否为空。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        • 2018-09-11
        • 2021-01-01
        相关资源
        最近更新 更多