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 BankAccount
2 def initialize(balance)
# Der Kontostand liegt in einer Instanzvariable
3 @balance = balance
4 end
5
6 def deposit(amount)
# Addiert den Betrag, nachdem eine private Hilfsmethode ihn geprüft hat
7 @balance += validate_amount(amount)
8 end
9
10 def withdraw(amount)
# Zieht nur ab, wenn der Kontostand den Betrag deckt
11 @balance -= validate_amount(amount) if sufficient_funds?(amount)
12 end
13
14 def balance
# Gibt den Kontostand als formatierten String zurück
15 format_currency(@balance)
16 end
17
# Alle unterhalb dieser Zeile definierten Methoden sind privat
18 private
19
20 def validate_amount(amount)
# Negative Beträge oder null zählen als 0
21 amount > 0 ? amount : 0
22 end
23
24 def sufficient_funds?(amount)
# true, wenn der Kontostand mindestens dem Betrag entspricht
25 @balance >= amount
26 end
27
28 def format_currency(amount)
# Setzt ein Dollarzeichen vor die Zahl
29 "$#{amount}"
30 end
31end
32
33account = BankAccount.new(100)
# 100 + 50 = 150
34account.deposit(50)
# Gibt "$150" aus; ein direkter Aufruf von account.format_currency löst NoMethodError aus
35puts account.balance

Ausgabe

$150
Diesen Code tippen üben

Ü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

Weitere Ruby-Beispiele auf Level 5

← Ruby-Tippübungen