使用方法(Ruby)创建后,将新属性添加到Object

时间:2017-11-10 00:14:59

标签: ruby object

我尝试使用对象类中的方法创建对象后添加属性。如果可能的话,我想将此代码放在def set_sell_by和def get_sell_by方法中。所以,最后我想做apple.set_sell_by(10),然后通过执行apple.get_sell_by获取该值,以检查该项目是否有5天或更短的时间来卖掉它。



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
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

Ruby在这方面非常宽松。只需使用@访问变量,如果它不存在,则会创建。

def set_sell_by
    @sell_by = value
    self
end