Sichtbarkeit von Methoden in Ruby
Level 5502 Tastenanschläge
BankAccount stellt deposit, withdraw und balance bereit; die Hilfsmethoden nach private lassen sich nur innerhalb des Objekts aufrufen.
Ruby-Code
1class BankAccount2 def initialize(balance) # Der Kontostand liegt in einer Instanzvariable3 @balance = balance4 end5 6 def deposit(amount) # Addiert den Betrag, nachdem eine private Hilfsmethode ihn geprüft hat7 @balance += validate_amount(amount)8 end9 10 def withdraw(amount) # Zieht nur ab, wenn der Kontostand den Betrag deckt11 @balance -= validate_amount(amount) if sufficient_funds?(amount)12 end13 14 def balance # Gibt den Kontostand als formatierten String zurück15 format_currency(@balance)16 end17 # Alle unterhalb dieser Zeile definierten Methoden sind privat18 private19 20 def validate_amount(amount) # Negative Beträge oder null zählen als 021 amount > 0 ? amount : 022 end23 24 def sufficient_funds?(amount) # true, wenn der Kontostand mindestens dem Betrag entspricht25 @balance >= amount26 end27 28 def format_currency(amount) # Setzt ein Dollarzeichen vor die Zahl29 "$#{amount}"30 end31end32 33account = BankAccount.new(100)# 100 + 50 = 15034account.deposit(50)# Gibt "$150" aus; ein direkter Aufruf von account.format_currency löst NoMethodError aus35puts account.balanceAusgabe
$150
Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.
Symbole in diesem Code
Die Symbole, die du in diesem Ruby-Code tippst, und wie oft sie vorkommen.
(× 12)× 12_× 7@× 5=× 5?× 3.× 3"× 2>× 2-× 1