所以我写了一个简单的产品类并从该类中实例化。
#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)”有点令人困惑,因为我是根据在线研究和书籍编写的,但如果我能对此有所澄清,那将会很有帮助。