patternrubyMinor
Determining if a product is taxable or imported
Viewed 0 times
determiningtaxableproductimported
Problem
This should tell me whether the product is taxable or imported. Name should indicate if the product is imported or certain keywords should tell that the product is non-taxable (chocolates, book, pills).
Could you please review the following class products?
Could you please review the following class products?
class Product
NON_TAXABLE = [/chocolates/, /book/, /pills/]
def initialize(product_name)
@product_name = product_name
end
def is_taxable?
taxable = false
NON_TAXABLE.each { |x| taxable = x.match(@product_name) if taxable }
!taxable
end
def is_imported?
/imported/.match(@product_name)
end
endSolution
Your
It's still possible to make it simpler using Ruby functions on arrays.
This means: if my product is not among the tax-free products, then it is taxable.
is_taxable? function code does not seem to work. The issue is that taxable is never going to be true, so you'll never assign a new value. You want to write if !taxable instead. Your code becomes:def is_taxable?
taxable = false
NON_TAXABLE.each { |x| taxable = x.match(@product_name) if !taxable }
!taxable
endIt's still possible to make it simpler using Ruby functions on arrays.
def is_taxable?
NON_TAXABLE.none? { |x| x.match(@product_name) }
endThis means: if my product is not among the tax-free products, then it is taxable.
Code Snippets
def is_taxable?
taxable = false
NON_TAXABLE.each { |x| taxable = x.match(@product_name) if !taxable }
!taxable
enddef is_taxable?
NON_TAXABLE.none? { |x| x.match(@product_name) }
endContext
StackExchange Code Review Q#22699, answer score: 5
Revisions (0)
No revisions yet.