I’m trying to push an element to the end of this array and I get an error I don’t understand.
main.rb:
require 'shop.rb'
so = Shop.new()
so.get(2)
so.get(1)
shop.rb
class Shop
def new()
@products = []
end
def get(product)
@products.push(product)
end
end
error:
NoMethodError: undefined method `push' for nil:NilClass
In Ruby, the constructor is
initialize, notnew. But you still usenewto create an object, e.g.Checkout.new.Also, the parentheses after method names are optional, and generally avoided in Ruby when there are no arguments.