1
I have the following Ruby codes in three different files. Follow them:
Rb program.
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 up 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 would like to know how I should proceed to remedy the error.
Just what I needed! I’m new to Ruby and I end up having doubts about it. The link you informed me helped me a lot to understand more about it. Thank you very much for all the help and attention! :)
– Matheus Portela