所以我写了一个简单的产品类,并从类中实例化。红宝石方法定义
#This class defines a product
#It provides a method that can be used to provide a discount on any given instance of a product
class Product
attr_reader :name, :description, :price
def initialize (name, description, price)
@name = name
@description = description
@price = Float(price)
end
def price=(sale_price)
@price = sale_price
end
def to_s
"Name: #{@name}, Description: #{@description}, Price: #{@price}."
end
end
my_product = Product.new("redshoes","These are beautiful",50.00)
my_product.price = my_product.price * 0.50
puts "The new sale price of #{my_product.name} is #{my_product.price}"
我有一个问题我需要澄清那就是当我这样定义一个方法:
def price=(sale_price)
@price = sale_price
end
我定义的方法,并在同一时间将其分配给一个变量。第一行“def price =(sale_price)”有点令人困惑,因为我基于在线研究和书籍撰写了这篇文章,但如果我可以对此进行一些澄清,这将会有所帮助。
谢谢你们。@@ Guilherme Bernal由于您提到两种方法相同,所以我对代码进行了更改,但是我得到的错误数量参数错误(1代表0)(ArgumentError) def price(sale_price) @price = sale_price end def to_s “名称:#{@ name},描述:#{@ description},价格:#{@ price}。” 结束 结束 my_product = Product.new( “redshoes”, “这是美丽的”,50.00) my_product.price = my_product.price * 0.50 看跌期权“的#新的销售价格{} my_product.name是# {my_product.price}“ – user2912496