2013-08-04 38 views
0

嗨我堅持定義實例方法。本教程要求:LearnStreet Ruby初學者課程9.12

在BankAccount類中定義一個稱爲balance的方法,該方法返回餘額。

的代碼有:

class BankAccount 
     def initialize(balance) 
      @balance = balance 
     end 
    # your code here 
end 

我,什麼問題是問真糊塗。任何幫助,將不勝感激......

回答

2

本教程要求你定義一個「getter」爲BankAccount類:

class BankAccount 
     def initialize(balance) 
      @balance = balance 
     end 
     def balance 
     @balance # remember that the result of last sentence gets returned in ruby 
     end 
end 

然後,你可以做

bankAccount = BankAccount.new 22 # the value 22 is the balance that gets passed to initialize 
bankAccount.balance # 22 

現在,如果本教程所要求的是一種班級方法(對我來說它不是很清楚),你應該這樣做:

 def self.balance # self is here so you define the method in the class 
     @balance 
     end 

然後,你可以做BankAccount.balance

1

好吧,讓我們的示例代碼:

class BankAccount 
     def initialize(balance) 
      @balance = balance 
     end 
    # your code here 
end 

在這裏你要定義一個BankAccount類定義BankAccount#initialize方法(也稱爲構造函數)將被自動調用上經由BankAccount::new一個BankAccount對象的創建:

BankAccount.new(123) 

在上面的例子@balance將被設置爲123@balance是一個實例變量(注意名稱前面的@),這意味着您可以在您定義的任何方法內使用每個對象來訪問它

要返回變量,如鍛鍊問,你可以使用關鍵字returnBankAccount#balance方法中,如下所示:

def balance 
    return @balance 
end 

Ruby的語法也可略return(因爲它的目的是始終返回從一個方法的最後計算的表達式),導致更簡潔的語法:

def balance 
    @balance 
end 

對於這種吸氣劑的方法(=方法,返回一個實例變量)有一個輕鬆實用程序:attr_reader,您可以使用如下:

class BankAccount 

    attr_reader :balance 

    def initialize(balance) 
     @balance = balance 
    end 

end 

不過不用擔心很快,你可能會了解到以上。 快樂學習。

+0

謝謝你的解釋,這是非常有益的。 –

0
class BankAccount 

    attr_reader :balance 

    def initialize(balance) 
     @balance = balance 
    end 

end 

附加attr_reader:平衡