I am newbie in Ruby, I cannot find the bug on my financial program.

The question is related to local variable in block.

Here is a quick example:

a = 5000

r = 0.06

p = 100

(1…5).each {|i|

puts "#{i}\t#{a}\t#{a*r}\t#{p}" # <-- the #{a} is not print
correctly, why?
a -= (p - a*r)

}

Thanks for help.

## ···

Below is my financial program, skip it if you are not interesting.

In fact, I want to know how the bank calcule the payment per year for

a loan.

Below is my quick and throw away program. You can play it.

BTW: If anyone know the web site to do this calculation. (Maybe some

formula out there)

My result still a little bit different then the bank.

(because tax? or other fee charge by the bank … )

=begin

Calculate the payment for loan.

This program try to find out the payment per year.

It uses array of 2 elements to simulate symbolic algebra

calculation.

[x,y] => x is real value, y is coefficient of payment per year.

Note: no robust error checking for input value. GUI todo.

=end

#Re-define Array for our use. Note, it may-be better create our own

class.

class Array

def *(int)
self.map{|x| x*int}

end

def +(array)

x = self.dup

self.each_index{|i| x[i] += array[i]}

x

end

def -(array)

self + (array * -1)

end

end

print "Capital = ? "

capital_in = gets.to_i

capital = [capital_in, 0] # to our format

print "Years = ? "

years = gets.to_i

print "interest rate = ? "

rate = gets.to_f

# calculate the sum of each year’s interest

sum_int = [0,0]

(1…years).each {

interest = capital * rate

sum_int += interest

capital -= ([0,1] - interest) # [0,1] means the payment for a year

}

# Now, find out what is exactly the payment per year (= X).

# We have formula like: total payment = capital + sum interest

# ==> years * payment/years = capital_in + sum_int

# ==> years * X = capital_in + [total interest, coef of X ]

# ==> years * X = capital_in + sum_int[0] + sum_int[1] * X

# ==> X = (capital_in + sum_int[0]) / (years - sum_int[1])

payment = (capital_in + sum_int[0]) / (years - sum_int[1])

# now, output in good format.

puts “-” * 30

puts "you loan from bank:"

puts "capital = #{capital_in}"

puts "years = #{years}"

puts "interest rate = #{rate}"

puts

puts "payment/year = #{payment}, payment/month = #{payment/12}"

puts “total payment = #{payment*years}"
puts "total bank gain = #{payment*years-capital_in}”

#=begin More detail information for each year

capital = capital_in

puts “\nYear\tCapital\tInterest\tPayment”

(1…years).each {|year|

# puts "#{year}\t#{capital}\t#{capital*rate}\t#{payment}" # <–
the #{capital} is not print correctly, why ??
printf “%i\t%.2f\t%.2f\t%.2f\n”, year, capital, (capital*rate),

payment

capital -= (payment - capital*rate)

}

#=end