2013-10-23 48 views
1

所以我寫了一個簡單的產品類,並從類中實例化。紅寶石方法定義

#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)」有點令人困惑,因爲我基於在線研究和書籍撰寫了這篇文章,但如果我可以對此進行一些澄清,這將會有所幫助。

+0

謝謝你們。@@ 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

回答

0

這是如何紅寶石做setter方法。請記住,不要求方法名稱和變量名稱匹配,也不要求實際進行任何分配,儘管這在大多數情況下可能是很好的做法。

,但你可以有:

def confuse=(ignore_me) 
    puts "Silly human, #{ignore_me} is being ignored!" 
end 

這將被調用任何時候你有

object.confuse = something 

和不執行任何實際的分配。

1

這只是方法的名稱。

def set_price(p) 
    @price = p 
end 

或:

def price=(p) 
    @price = p 
end 

你調用這個方法:

product.set_price(100) 
product.price=(100) 

看到了嗎?不用找了。魔術時顯示紅寶石讓你省略括號和平等和名稱的其餘部分之間加空格:

product.price = 100 

這僅僅是一個常用的方法調用。沒有什麼奇特的事情發生。

+2

Nit-pick:這個解釋並不完全準確。 Ruby不僅允許你省略parens並在setter方法名稱的等號周圍添加空格 - setter語法是一個特殊的構造,它調用底層的setter方法,但不同於直接調用它。例如,假設我們的setter是'def price =(p)@price = p; 42結束'。如果寫'product.price = 100''等於'product.send(:price =,100)',我們預計這兩個調用返回42,而'product.price = 100'返回100而'product'。發送(:price =,100)'返回42。 – Chuck

1

我認爲如果你明白def實際上在做什麼,它會更有意義。在def price=(sale_price)的示例中,「price =」是您在Product類中定義的方法的名稱。當您撥打my_product.price =時,您正在調用您定義的方法「price =」。

除非將實例變量@price設置爲等於方法的輸入(變量sale_price),否則實際上並沒有更改任何值。

原因my_product.price(不帶等號)的工作原理是,因爲你已經定義的屬性使用attr_reader :price,這是給你的讀訪問實例變量@price一個有用的方式稱爲:price

希望有所幫助。