I have the following Ruby codes in three different files. Follow them:
programa.rb
require_relative "product"
require_relative "store"
cd = Product.new("CD",20.5)
pinico = Product.new("Pinico",30.6)
store = [cd,pinico]
test = Store.new(store)
puts test
product.rb
class Product
attr_accessor :name, :price
def initialize(name,price)
@name = name
@price = price
end
def to_s
"name: #{@name} - price: #{@price}"
end
end
store.rb
class Store
attr_accessor :product, :total
def initialize(product)
@product = product
end
total = 0
def to_s
product.each do |product|
puts product.price
total += product.price
end
"Soma total dos produtos: #{@total}"
end
end
From the store.rb file, I would like to sum the total value of the products and return them to the program.rb file, where I build the class. When I run the same file on the terminal, it returns me the following error:
/home/cabox/workspace/test/store.rb:12:in 'block in to_s': undefined method '+' for nil:NilClass (NoMethodError)
from /home/cabox/workspace/test/store.rb:10:in 'each'
from /home/cabox/workspace/test/store.rb:10:in 'to_s'
from programa.rb:9:in 'puts'
from programa.rb:9:in 'puts'
from programa.rb:9:in '<main>'
I'd like to know how to proceed to fix the error.