我根据Treehouse.com中的项目编写了以下代码:
class Buxfer
attr_reader :name
def initialize(name)
@name = name
@transactions = []
add_transaction("Opening Balance", 0)
end
def add_transaction(description, amount)
@transactions.push(description: description, amount: amount)
end
def credit(description, amount)
add_transaction(description, amount)
end
def debit(description, amount)
add_transaction(description, -amount)
end
def balance
balance = 0.0
@transactions.each do |transaction|
balance += transaction[:amount]
end
return balance
end
def print_account
puts "-" * 60
puts "Account Holder Name: #{name}".ljust(30)
puts "-" * 60
puts "-" * 60
puts "Description".ljust(30) + "Amount".rjust(30)
puts "-" * 60
@transactions.each do |item|
puts item[:description].ljust(30) + sprintf("%0.2f", item[:amount]).rjust(30)
end
puts "-" * 60
puts "Balance: #{balance}".rjust(60)
puts "-" * 60
end
end
helios = Buxfer.new("Helios")
helios.debit("Rent", 2000)
helios.debit("Food", 800)
helios.debit("Gym", 45)
helios.credit("Salary", 8000)
puts "\n"
puts "\n"
puts helios.inspect
puts "\n"
puts "\n"
puts helios.print_account
创建方法add_transaction
。
它需要两个参数,并push
将它们添加到@transactions
。我不确定(description: description, amount: amount)
会发生什么。这是一个散列,其中符号作为键,值是字符串还是整数?
credit
(和debit
)方法
def credit(description, amount)
add_transaction(description, amount)
end
我创建了带有两个参数的credit
方法。不确定add_transaction
中发生了什么。它被推送到@transactions
。
答案 0 :(得分:0)
在add_transaction
中,请点击此处:
@transactions.push(description: description, amount: amount)
在initialize
方法中初始化时,@transactions
是一个数组(默认为空)。 Array#push
是将给定对象推送到数组末尾的方法。这就是将传递的参数添加到@transactions
数组的原因。由于push
方法的参数是键值对,因此推送的对象是哈希。
让它更清晰的例子:
@transactions = []
#=> []
@transactions.push(description: "somethign", amount: 100)
#=> [{:description=>"somethign", :amount=>100}]
答案 1 :(得分:0)
从你的问题本身中举例:
helios = Buxfer.new("Helios")
helios.debit("Rent", 2000)
helios.debit("Food", 800)
helios.debit("Gym", 45)
helios.credit("Salary", 8000)
puts "\n"
puts "\n"
puts helios.inspect
puts "\n"
puts "\n"
puts helios.print_account
在此每次您对信息进行贷记或借记时,金额都会添加到交易对象中。它基本上是在数组中推送对象,您可以稍后循环以获得帐户余额,如 print_account 方法中所做的那样。 所以事务对象看起来像这样:
@transactions = [{description: 'Rent', amount: -2000}, {description: 'Food', amount: -800}, {description: 'Gym', amount: -45}, {description: 'Salary', amount: 8000} ]