Reputation: 93
I am creating a takeaway restaurant database, which can be accessed by the Managers
of each store. One of the database tables in called Product
, and it has a column called product_name
. The product_name
is a string with multiple words. I'm trying to check whether the product_name
contains meat, and then tell the user whether it is or is not suitable for vegetarians.
This is the code I have. I was trying to create a meats
array, and check product_name
against it. I don't think the if not
statement is correct.
class Checkveg
def self.runcheck(product_name)
meats = ["lamb", "beef", "pork", "prawn", "chicken", "fish"]
meats.each { |item|
if product_name.include? item
puts "Not suitable for vegans or vegetarians"
end
}
puts "Suitable for vegans or vegetarians" if not meats.include? product_name
end
end
**UPDATE:
I was able to fix it
noVeg = false
meats = ["lamb", "beef", "pork", "prawn", "chicken", "fish"]
meats.any? { |item|
if product_name.include? item
noVeg = true
break
end
}
if noVeg == true
puts "Not suitable for vegetarians"
else
puts "Suitable for vegetarians"
end
Upvotes: 1
Views: 89
Reputation: 21130
Another option is to create a regex using the meats
array.
meats_regex_string = meats.map(&Regexp.method(:escape)).join('|')
meats_regex = Regexp.new(meats_regex_string)
# or /#{meats_regex_string}/
product_name.match?(meats_regex)
You can leave out .map(&Regexp.method(:escape))
if you know your strings don't contain any regex special characters like (
, *
, ?
, |
, etc.
If you don't care about the character casing use:
meats_regex = Regexp.new(meats_regex_string, Regexp::IGNORECASE)
# or /#{meats_regex_string}/i
Upvotes: 2
Reputation: 11193
I'd suggest, first to extract the words from the product name. I used the regex from a good example by Cary Swoveland for this method. But you can use whatever regex fits best for you:
product_name = "Chicken_Wings 1"
product_words = product_name.scan(/[[:alpha:]](?:(?:[[:alpha:]]|\d|')*[[:alpha:]])?/x).map(&:downcase)
#=> ["chicken", "wings"]
Then check if none of the product_words
is included in meats
array:
no_veg = product_words.none? { |w| meats.include? w }
#=> false
In this case product_name = "Carrots and onions"
, no_veg = true
.
Upvotes: 2
Reputation: 33327
You are not using the any?
method properly. You should use it's return value like this:
#!/usr/bin/env ruby
meats = ["lamb", "beef", "pork", "prawn", "chicken", "fish"]
product_name = "Beef curry"
noVeg = meats.any? do |item|
product_name.downcase.include? item
end
if noVeg == true
puts "Not suitable for vegetarians"
else
puts "Suitable for vegetarians"
end
I also added downcase
since in the comment above you wrote beef with a capital b
.
Upvotes: 2