1

I am trying to add an attribute to an object after it's been created using a method from within the object Class. I'd like to put this code in the def set_sell_by and def get_sell_by methods, if this is possible. So, in the end I'd like to do apple.set_sell_by(10) and then get that value later by doing apple.get_sell_by to check if the item has 5 days or less left to sell it.

class Grocery_Inventory
	attr_accessor :product, :store_buy, :quantity, :serial_number, :customer_buy
	def initialize(product, store_buy, quantity, serial_number, customer_buy)
		@product = product
		@store_buy = store_buy
		@quantity = quantity + 5
		@serial_number = serial_number
		@customer_buy = customer_buy
	end
	
	def get_product_name
		p product
		self
	end
	
	def get_cost_customer
		p "$#{customer_buy}"
		self
	end

	def get_product_quantity
		p "You have #{quantity} #{product}"
		self
	end

	def set_sell_by
		#some code...
		self
	end

	def get_sell_by
		if sell_by < 5
			p "You need to sell this item within five days."
			self
		else
			p "Item doesn't currently need to be sold."
			self
		end
	end
end

apples = Grocery_Inventory.new("apples", 1.00, 5, 123, 0.25)
apples.get_product_name
apples.get_cost_customer
apples.get_product_quantity

1
  • You already do exactly what you are asking about in your initialize method. So, clearly, it is possible. Also, what happened when you tried it? Commented Nov 10, 2017 at 10:44

1 Answer 1

2

Ruby is very lax in this regard. Simply access a variable with @and if it doesn't exist it will be created.

def set_sell_by
    @sell_by = value
    self
end
Sign up to request clarification or add additional context in comments.

1 Comment

To be more precise: every object is always created empty. The only possible way to add an instance variable to an object is after it is created, and (almost) the only possible way to execute code in Ruby is using methods, so pretty much every instance variable ever is added after the object is created using a method. Typically, those methods are either called <instance_variable_name>= or initialize.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.