HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Determining if a product is taxable or imported

Submitted by: @import:stackexchange-codereview··
0
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?

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
end

Solution

Your 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
end


It's still possible to make it simpler using Ruby functions on arrays.

def is_taxable?
  NON_TAXABLE.none? { |x| x.match(@product_name) }
end


This 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
end
def is_taxable?
  NON_TAXABLE.none? { |x| x.match(@product_name) }
end

Context

StackExchange Code Review Q#22699, answer score: 5

Revisions (0)

No revisions yet.