How to get the users input and check against the items in an array?
I want the user to enter their style of beard and then I will have it checked against a list of beards in an array of style of beards. This is something extra I wanted to do and i'm not sure how to work it out. The only item I came across to something close to it is the (include?) but I want to have:
(array name).include? (value input from user)
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
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
beards = ['long','short','ginger','dirty']
selected = ['ginger']
selected - beards
=> []
(selected - beards) returns elements from selected that do not exist in beards. Ginger is in the list, so we get an empty array back.
beards = ['long','short','ginger','dirty']
selected = ['ginger', 'fluffy']
selected - beards
=> 'fluffy'
My second example returns fluffy because it's not in the list. You can wrap this in its own method that checks if the returning array is empty or not.
This approach is great because not only can you check to see if the selected elements exist, it'll return those that don't, which is helpful if you want to return some sort of meaningful error.
链接地址: http://www.djcxy.com/p/25690.html上一篇: Array.include? myVariable无法按预期工作
下一篇: 如何获取用户输入并检查数组中的项目?