Undefined local variable or method

Asked

Viewed 1,601 times

0

class ProdutItem
  attr_reader :item, :price_unit, :qtde

  def initialize(item, price_unit, qtde)
    @item = item
    @price_unit = price_unit
    @qtde = qtde
  end

  def calc_qtde
     (price_unit * qtde)
  end

end

 prod = ProdutItem.new("A", 0.50, 3)
 puts prod.calc_qtde

class CalcDiscount
  attr_reader :discount

  def initialize(discount)
    @discount = discount
  end

  def calc_desc
    (price_unit * qtde) - discount
  end
end

desc = CalcDiscount.new(0.20)
puts desc.calc_desc

When I run this my above code returns the following error msg:

teste_04.Rb:29:in calc_desc': undefined local variable or method price_unit' for # (Nameerror) from teste_04.Rb:34:in `'

Eu nao consigo identificar o erro. Alguem poderia me ajudar?
  • I believe you are not creating the variable : "calc_desc"

  • price_unit does not exist within the class CalcDiscount only in the ProdutItem and if it exists it must be accessed with @

  • Isac, even add the price_unit, continues with error: teste_04.Rb:24:in `initialize': Wrong number of Arguments (Given 1, expected 2) (Argumenterror)

1 answer

0


I did it that way and it worked:

class ProdutItem
  attr_reader :item, :price_unit, :qtde

  def initialize(item, price_unit, qtde)
    @item = item
    @price_unit = price_unit
    @qtde = qtde
  end

  def calc_qtde
    (price_unit * qtde)
  end

end

class CalcDiscount
  attr_reader :discount

  def initialize(discount)
    @discount = discount
  end

  def calc_desc(product)
    (product.price_unit * product.qtde) - discount
  end
end


prod = ProdutItem.new("A", 0.50, 3)
puts prod.calc_qtde

desc = CalcDiscount.new(0.20)
puts desc.calc_desc(prod)

To calculate the discount, the method needs the unitary price and the quantity of the product. Because of this, I added the parameter product in the method that calculates the discount so that we can have access to information we want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.